Javascript重新创建多维数组

时间:2018-03-17 17:07:02

标签: javascript arrays multidimensional-array

我将以下多维数组存储在名为posts

的变量中
{ID: 141, categories: ["candy", "fruits", "vegetables"]}
{ID: 142, categories: ["fruits"]}
{ID: 143, categories: ["candy", "vegetables"]}

是否可以仅在类别中包含candy的项目创建新数组?

所以新的posts变量将包含以下数组:

{ID: 141, categories: ["candy", "fruits", "vegetables"]}
{ID: 143, categories: ["candy", "vegetables"]}

1 个答案:

答案 0 :(得分:3)

您可以使用filter()includes()方法并返回新数组。

const data = [{ID: 141, categories: ["candy", "fruits", "vegetables"]}, {ID: 142, categories: ["fruits"]}, {ID: 131, categories: ["candy", "vegetables"]}]

const result = data.filter(({categories}) => categories.includes('candy'));
console.log(result)