获取js中嵌套对象的所有键
我有一个非常简单的问题,假设下面的对象
const x={a:{b:"b"},c:{b:"b"}}
1)我想要一个方法来返回嵌套对象中的所有键,例如[“a”,“b”,“c”] 2)我想要一个方法来返回我的特定键的所有路径,例如 b=>["a","c"] 使用lodash,我们有方法_.get(obj,path)
,它通过我们传递给get方法的路径返回对象值,但有时我们没有路径或路径模糊怎么办 下面的代码以某种方式解决问题
const findPath = (ob, key) => {
const path = [];
const keyExists = (obj) => {
if (!obj || (typeof obj !== "object" && !Array.isArray(obj))) {
return false;
}
else if (obj.hasOwnProperty(key)) {
return true;
}
else if (Array.isArray(obj)) {
let parentKey = path.length ? path.pop() : "";
for (let i = 0; i < obj.length; i++) {
path.push(`${parentKey}[${i}]`);
const result = keyExists(obj[i], key);
if (result) {
return result;
}
path.pop();
}
}
else {
for (const k in obj) {
path.push(k);
const result = keyExists(obj[k], key);
if (result) {
return result;
}
path.pop();
}
}
return false;
};
keyExists(ob);
return path.join(".");
}
上面的代码的问题是:1)不干净 2)不返回所有路径,例如 x={a:{b:"b"},c:{b:"b"}}仅返回“a”
i have very simple question assume bellow object
const x={a:{b:"b"},c:{b:"b"}}
1)I want a method to return all of keys in my nested object eg ["a","b","c"]
2)I want a method to return all paths of my specific key eg for b=>["a","c"]
using lodash we have method _.get(obj,path)
that return object value by the path we pass to get method but what about times we haven't path or path is vague
bellow code solve problem somehow
const findPath = (ob, key) => {
const path = [];
const keyExists = (obj) => {
if (!obj || (typeof obj !== "object" && !Array.isArray(obj))) {
return false;
}
else if (obj.hasOwnProperty(key)) {
return true;
}
else if (Array.isArray(obj)) {
let parentKey = path.length ? path.pop() : "";
for (let i = 0; i < obj.length; i++) {
path.push(`${parentKey}[${i}]`);
const result = keyExists(obj[i], key);
if (result) {
return result;
}
path.pop();
}
}
else {
for (const k in obj) {
path.push(k);
const result = keyExists(obj[k], key);
if (result) {
return result;
}
path.pop();
}
}
return false;
};
keyExists(ob);
return path.join(".");
}
problems with above code are:1)is not clean 2)don't return all paths for example in x={a:{b:"b"},c:{b:"b"}} return just "a"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以采用递归方法并检查键是否存在,然后返回此键,包装在嵌套数组中或返回嵌套对象的结果并将其与实际键映射或返回一个空数组,这不是平面的条目地图。
You could take a recursive approach and check if the key exists, then return this key, wrapped in a nested array or return the result of nested objects and map this with the actual key or return an empty array, which is no entry for a flat map.