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 に答える