Find by key deep in a nested array

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

Let\'s say I have an object:

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


        
17条回答
  •  无人及你
    2020-11-22 15:57

    I would try not to reinvent the wheel. We use object-scan for all our data processing needs. It's conceptually very simple, but allows for a lot of cool stuff. Here is how you would solve your specific question

    const objectScan = require('object-scan');
    
    const find = (id, input) => objectScan(['**'], {
      abort: true,
      rtn: 'value',
      filterFn: ({ value }) => value.id === id
    })(input);
    
    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: {}
          }]
        }]
      }]
    }];
    
    console.log(find('1', data));
    // => { image: 'http://www.asdasd.com', title: 'Sandals', id: '1', content: {} }
    

提交回复
热议问题