如何在嵌套数组中获取项目 [英] How to get items inside nested arrays

查看:73
本文介绍了如何在嵌套数组中获取项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的数组:

I have an array like this:

[
  {
    "id": 1,
    "name": "Vehicle",
    "subCategories": [
      {
        "subCategoryId": 1,
        "subCategoryName": "Car"
      }
    ]
  },
  {
    "id": 2,
    "name": "Delivery",
    "subCategories": [
      {
        "subCategoryId": 1,
        "subCategoryName": "Furniture"
      }
    ]
  },
  {
    "id": 3,
    "name": "Home Services",
    "subCategories": [
      {
        "subCategoryId": 1,
        "subCategoryName": "Lawn Mowing"
      }
    ]
  }
]

我想从称为子类别的单个数组中获取所有类别的所有子类别.

I want to get all subcategories from all categories inside a single array called subcategories.

我尝试了map,reduce,concat等,但似乎无法获得预期的结果.

I have tried map, reduce, concat, etc. but cannot seem to get the desired result.

推荐答案

您可以使用解构从每个对象中提取 subCategories 数组,然后使用 .flatMap 进行展平将其放入数组,如下所示:

You could use destructuring to extract the subCategories array from each object and then use .flatMap to flatten it into an array like so:

const arr = [{id:1,name:"Vehicle",subCategories:[{subCategoryId:1,subCategoryName:"Car"}]},{id:2,name:"Delivery",subCategories:[{subCategoryId:1,subCategoryName:"Furniture"}]},{id:3,name:"Home Services",subCategories:[{subCategoryId:1,subCategoryName:"Lawn Mowing"}]}];

const subcategories = arr.flatMap(({subCategories}) => subCategories);
console.log(subcategories);

如果您希望与浏览器更兼容,可以通过将每个 subCategories 数组的内容散布到一个累积数组中,在初始数组上使用 .reduce():

If you want something a little more browser compatible, you can use .reduce() on your initial array by spreading the contents of each subCategories array into an accumulating array:

const arr = [{id:1,name:"Vehicle",subCategories:[{subCategoryId:1,subCategoryName:"Car"}]},{id:2,name:"Delivery",subCategories:[{subCategoryId:1,subCategoryName:"Furniture"}]},{id:3,name:"Home Services",subCategories:[{subCategoryId:1,subCategoryName:"Lawn Mowing"}]}];
const subcategories = arr.reduce((res, {subCategories}) => [...res, ...subCategories], []);
console.log(subcategories);

这篇关于如何在嵌套数组中获取项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆