Find by key deep in a nested array

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

Let\'s say I have an object:

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


        
17条回答
  •  生来不讨喜
    2020-11-22 16:02

    Just use recursive function.
    See example below:

    const data = [
      {
        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: {},
                  }
                ]
              }
            ]
          }
        ]
      }
    ]
    
    function _find(collection, key, value) {
      for (const o of collection) {
        for (const [k, v] of Object.entries(o)) {
          if (k === key && v === value) {
            return o
          }
          if (Array.isArray(v)) {
            const _o = _find(v, key, value)
            if (_o) {
              return _o
            }
          }
        }
      }
    }
    
    console.log(_find(data, 'channel_id', 'dsa2'))

提交回复
热议问题