我有一个像这样结构的 JavaScript 对象;
brand: {
group: {
subGroup: {
items: []
},
otherSub: {
items: []
}
}
}
给定一个键数组 ['brand'、'group'、'newGroup'、'newSubGroup'],我想将键拆分为找到的键和丢失的键。所以对于上面的结构我应该返回;
present = ['brand', 'group']
missing = ['newGroup', 'newSubGroup']
我正在使用 ES6 并且有 lodash 可用,但正在努力寻找一种干净的方法来生成它。
这不仅仅是检查是否存在,而是递归地查找键并返回存在的键和剩余的键。
最佳答案
这是一种非常粗略的工作方式。
const find = (keys, obj) => {
const string = JSON.stringify(obj);
return keys.reduce(({ present, missing }, key) => {
const match = string.match(new RegExp(`"${key}":`));
if (match) {
present.push(key);
} else {
missing.push(key);
}
return { present, missing };
}, { present: [], missing: [] });
}
关于javascript - 递归查找对象上的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45197340/