在 JavaScript/ES6/ES7 中迭代数组中的嵌套值

Iterate Nested Value in Array in JavaScript/ES6/ES7

我需要在 javascript 中迭代一个嵌套值。

我想要的输出应该是这样的

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) }

你的问题虽然不清楚,但我假设你正在搜索 ID 属性 并想获取 ID 的值并创建一个数组。你可以这样试试-

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}

您在找这样的东西吗?

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 final = results.reduce((p, n) => {
  // Get all object's array props and then reduce their keys
  const mapped = Object.keys(n).filter((key) => Array.isArray(n[key])).reduce((arr, key) => [
      ...arr,
      // Get the array by using the object's key, filter out all objects which don't have
      // an 'ID' key, and return a new array which only contains the x.ID property
      ...n[key].filter((x) => x.ID).map((x) => x.ID)
  ], []);
  
  return [
    ...p,
    ...mapped,
  ];
}, []);

console.log('final', final);

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"}]}];


let arr = results.flatMap(e => Object.values(e).filter(n => Array.isArray(n))) // at this stage you have an array of arrays
         .flat() // at this stage you have flat array from previous stage
         .map(s => s.ID) // Now you pick the IDs

console.log(arr)