JS获取一个数组内的所有数组

JS get all the arrays within an array

我有一个如下所示的对象:

const test = {
  leagues: [
    {
      timezone: "GMT",
      date: "1/2/2",
      premierLeague: [
        { name: "Liverpool", age: 1892 },
        { name: "Manchester Utd", age: 1878 }
      ],
      laLiga: [
        {
          team: "Real Madrid",
          stadium: "Bernabeu"
        },
        {
          team: "Barcelona",
          stadium: "Camp Nou"
        }
      ]
    }
  ]
};

我希望结果看起来像

const result = [
  { name: "Liverpool", age: 1892 },
  { name: "Manchester Utd", age: 1878 },
  {
    team: "Real Madrid",
    stadium: "Bernabeu"
  },
  {
    team: "Barcelona",
    stadium: "Camp Nou"
  }
];

我曾尝试使用 flat(),但在 leagues 中获取数组时遇到问题。结果将是动态的,因此我需要能够获取 leagues 内的所有数组。任何人都可以指出正确的方向吗?

如果您的对象结构没有比这更深,那么这个长 one-liner 应该可以工作:

const result = test.leagues.reduce((arr, obj) => Object.values(val).reduce((innerArr, val) => Array.isArray(val) ? innerArr.concat(val) : innerArr, arr), []);

有点不打高尔夫球:

const result = test.leagues.reduce((arr, obj) => {
  return Object.values(val).reduce((innerArr, val) => {
    return Array.isArray(val)
      ? innerArr.concat(val) 
      : innerArr
  }, arr);
}), []);

您可能正在寻找

const result = test.leagues.flatMap(league =>
  Object.values(league).filter(Array.isArray).flat()
);

这听起来很奇怪,您最终会在同一个数组中得到不同形状的对象。我不确定你会如何处理。

您似乎在尝试连接本身就是数组的 test.leagues 的每个值。

const test = {
  leagues: [{
    timezone: "GMT",
    date: "1/2/2",
    premierLeague: [{
        name: "Liverpool",
        age: 1892
      },
      {
        name: "Manchester Utd",
        age: 1878
      }
    ],
    laLiga: [{
        team: "Real Madrid",
        stadium: "Bernabeu"
      },
      {
        team: "Barcelona",
        stadium: "Camp Nou"
      }
    ]
  }]
};


const output = [];
for (const league of test.leagues) {
  for (const key in league) {
    if (Array.isArray(league[key])) {
      // Push each element in `league[key]` onto `output`
      // so we don't have to flatten it later
      output.push(...league[key]);
    }
  }
}
console.log({
  output
});

好吧,我还要在这里加上我的 2 美分。我同意其他人的看法。看看这是否有效:

const test = {
  leagues: [
    {
      timezone: "GMT",
      date: "1/2/2",
      premierLeague: [
        { name: "Liverpool", age: 1892 },
        { name: "Manchester Utd", age: 1878 }
      ],
      laLiga: [
        {
          team: "Real Madrid",
          stadium: "Bernabeu"
        },
        {
          team: "Barcelona",
          stadium: "Camp Nou"
        }
      ]
    }
  ]
};

let finalArray = [];

function recursiveArr(obj, arrayToPush) {
    for(const [key, val] of Object.entries(obj)) {
    if(Array.isArray(obj[key])) {
      arrayToPush.push(obj[key]);
      continue;
    }
    
    const type = typeof obj[key];
    
    if(type === "object") {
       recursiveArr(obj[key], arrayToPush);
    }
  }
}

recursiveArr(test.leagues, finalArray);

console.log(finalArray.flat())