Find by key deep in a nested array

后端 未结 17 1483
礼貌的吻别
礼貌的吻别 2020-11-22 15:41

Let\'s say I have an object:

[
    {
        \'title\': \"some title\"
        \'channel_id\':\'123we\'
        \'options\': [
                    {
                 


        
17条回答
  •  自闭症患者
    2020-11-22 15:47

    Another (somewhat silly) option is to exploit the naturally recursive nature of JSON.stringify, and pass it a replacer function which runs on each nested object during the stringification process:

    const input = [{
      'title': "some title",
      'channel_id': '123we',
      'options': [{
        'channel_id': 'abc',
        'image': 'http://asdasd.com/all-inclusive-block-img.jpg',
        'title': 'All-Inclusive',
        'options': [{
          'channel_id': 'dsa2',
          'title': 'Some Recommends',
          'options': [{
            'image': 'http://www.asdasd.com',
            'title': 'Sandals',
            'id': '1',
            'content': {}
          }]
        }]
      }]
    }];
    
    console.log(findNestedObj(input, 'id', '1'));
    
    function findNestedObj(entireObj, keyToFind, valToFind) {
      let foundObj;
      JSON.stringify(input, (_, nestedValue) => {
        if (nestedValue && nestedValue[keyToFind] === valToFind) {
          foundObj = nestedValue;
        }
        return nestedValue;
      });
      return foundObj;
    };

提交回复
热议问题