Find value in javascript array of objects deeply nested with ES6

后端 未结 4 2107
星月不相逢
星月不相逢 2021-01-12 10:46

In an array of objects I need to find a value -- where key is activity : However the activity key can be dee

4条回答
  •  抹茶落季
    2021-01-12 11:18

    We now use object-scan for simple data processing tasks like this. It's really good once you wrap your head around how to use it. Here is how one could answer your questions

    const objectScan = require('object-scan');
    
    const find = (activity, input) => objectScan(['**'], {
      abort: true,
      rtn: 'value',
      filterFn: ({ value }) => value.activity === activity
    })(input);
    
    const activityItems = [{"name":"Sunday","items":[{"name":"Gym","activity":"weights"}]},{"name":"Monday","items":[{"name":"Track","activity":"race"},{"name":"Work","activity":"meeting"},{"name":"Swim","items":[{"name":"Beach","activity":"scuba diving"},{"name":"Pool","activity":"back stroke"}]}]}]
    
    console.log(find('scuba diving', activityItems));
    // => { name: 'Beach', activity: 'scuba diving' }
    

提交回复
热议问题