Find value in javascript array of objects deeply nested with ES6

后端 未结 4 2091
星月不相逢
星月不相逢 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:14

    While not as elegant as a recursive algorithm, you could JSON.stringify() the array, which gives this:

    [{"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"}]}]}]
    

    You could then use a template literal to search for the pattern:

    `"activity":"${activity}"`
    

    Complete function:

    findMatch = (activity, activityItems) =>
      JSON.stringify(activityItems).includes(`"activity":"${activity}"`);
    

    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',
              },
            ],
          },
        ],
      }
    ];
    
    findMatch = (activity, activityItems) =>
      JSON.stringify(activityItems).includes(`"activity":"${activity}"`);
    
    console.log(findMatch('scuba diving', activityItems)); //true
    console.log(findMatch('dumpster diving', activityItems)); //false

提交回复
热议问题