我将以下多维数组存储在名为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"]}
答案 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)