首页 > 解决方案 > 从数组中的对象中的数组中获取字符串值

问题描述

我有以下 JSON 对象:

var test = {
  data: [{
      itemID: 0,
      categories: [{
        id: 0,
        type: 'a',
        name: 'world'
      }, {
        id: 1,
        type: 'b',
        name: 'plants'
      }]
    },
    {
      itemID: 1,
      categories: [{
        id: 2,
        type: 'w',
        name: 'cars'
      }, {
        id: 3,
        type: 't',
        name: 'bicycles'
      }]
    }

  ]

};
console.log([].concat
.apply([],  test.data.map(item => item.categories.map(el => el.type))));

我想要做的是,获取数组中的所有类型。所以结果应该是这样的:

['a', 'b', 'w', 't']

我做了什么:

[].concat
.apply([],  test.data.map(item => item.categories.map(el => el.type)))

我觉得这可以更容易地完成。

有人知道更好的解决方案吗?

标签: javascriptjsonmapping

解决方案


您可以使用Array.prototype.map()Array.prototype.flat()

flat()方法创建一个新数组,其中所有子数组元素递归连接到指定深度。

深度是可选

指定嵌套数组结构应该展平的深度级别。默认为 1。

var test = {
  data: [{
      itemID: 0,
      categories: [{
        id: 0,
        type: 'a',
        name: 'world'
      }, {
        id: 1,
        type: 'b',
        name: 'plants'
      }]
    },
    {
      itemID: 1,
      categories: [{
        id: 2,
        type: 'w',
        name: 'cars'
      }, {
        id: 3,
        type: 't',
        name: 'bicycles'
      }]
    }

  ]

};

var type = test.data.map(item => item.categories.map(el => el.type)).flat();
console.log(type);


推荐阅读