javascript - 从数组中对象的数组中获取字符串值

标签 javascript json mapping

我有以下 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)))

我觉得这可以做得更容易。

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

最佳答案

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

The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

depth可选的

The depth level specifying how deep a nested array structure should be flattened. Defaults to 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);

关于javascript - 从数组中对象的数组中获取字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53079472/

相关文章:

javascript - 仅在关闭选项卡/窗口时弹出确认框

javascript - 根据它包含的表更改 div 高度

javascript - 在 html 中显示 javascript 变量

function - Julia:通过 map() 函数将关键字参数传递给函数

javascript - 如何检查数组中的数组中的变量是否已定义且不为空?

javascript - 切换按钮动画

java - 获取Json字段的值

jquery - 通过 ajax 调用 CouchDB 时得到空响应

parameters - 用于查询的 iOS RestKit 参数

algorithm - 批量地理定位数百万个IP