1

如果我有一个具有嵌套属性的对象。是否有一个函数可以搜索所有属性,以及具有其他对象值的属性(它们也有自己的属性)等等?

示例对象:

const user = { 
    id: 101, 
    email: 'help@stack.com', 
    info: { 
        name: 'Please', 
        address: {
            state: 'WX' 
        }
    }
}

在上面的对象中有一种方法我可以简单地调用类似的东西

console.log(findProp(user, 'state'));
console.log(findProp(user, 'id'));
4

2 回答 2

1

您需要的是一个递归函数,它查找匹配键的嵌套项(对象和数组)(我还为查找添加了一个数组):

var user = { id: 101, email: 'help@stack.com', info: {name: 'Please', address: {state: 'WX' }, contacts: [{'phone': '00000000'}, {'email': 'aaa@bbb.ccc'}]}}

function keyFinder(object, key) {
  if(object.hasOwnProperty(key)) return object[key];
  for(let subkey in object) {
    if(!object.hasOwnProperty(subkey) || typeof object[subkey] !== "object") continue;
    let match = keyFinder(object[subkey], key);
    if(match) return match;
  }
  return null;
}

console.log('id', keyFinder(user, 'id'));
console.log('state', keyFinder(user, 'state'));
console.log('phone', keyFinder(user, 'phone'));
console.log('notexisting', keyFinder(user, 'notexisting'));

Object.hasOwnProperty防止迭代或检索内置属性。

于 2018-06-07T20:17:46.703 回答
0
 function findProp(obj, search) {
   if(key in obj) return obj[key];
   for(const key in obj) {
     if(typeof obj[key] === "object" && obj[key] !== null) {
       const res = findProp(obj[key], search);
       if(res) return res;
     }
   }
}
于 2018-06-07T20:07:06.127 回答