Search code examples
javascriptecmascript-6ecmascript-2016

Iterate Nested Value in Array in JavaScript/ES6/ES7


I need to iterate a nested value in my javascript.

My wanted output should be like this

shows: ['food.order', 'drink.order', 'play.basketball', 'play.soccer']

const results = [
  {
    "ID": "shops",
    "Shopping": [
      {
        "ID": "food.order",
        "Name": "Food"
      },
      {
        "ID": "drink.order",
        "Name": "Drink"
      }
    ]
  },
  {
    "ID": "fun",
    "Sports": [
      {
        "ID": "play.basketball",
        "Name": "Basketball"
      },
      {
        "ID": "play.soccer",
        "Name": "Soccer"
      },
    ]
  }
];

console.log(results);

const final = { shows: results.map(data => data['key'].ID) }

Solution

  • Your question is not clear though, but I am assuming that you are searching for ID property and want to grab the value of the ID and make an array. You can try this way-

    const results = [{"ID": "shops", "Shopping": [{ "ID": "food.order", "Name": "Food"},{ "ID": "drink.order", "Name": "Drink"}]},{"ID": "fun", "Sports": [{ "ID": "play.basketball", "Name": "Basketball"},{ "ID": "play.soccer", "Name": "Soccer"}]}];
    
    const ans = results.reduce((acc, item) => {
    
      // Iterate throw the each item's properties
      Object.values(item).forEach(val => {
        
          // Filter out the objects which has the `ID` property and get the value of the `ID`.
          const ids = typeof val === 'object' && val instanceof Array
            ? val.filter(x => x.ID !== undefined).map(({ID}) => ID)
            : [];
    
          acc = [...acc, ...ids];
        
      });
    
      return acc;
    }, []);
    
    console.log(ans);
    .as-console-wrapper {min-height: 100%!important; top: 0}