在 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","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)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...