【问题标题】:combining array object properties to new array将数组对象属性组合到新数组
【发布时间】:2020-11-30 20:03:40
【问题描述】:

我有一个名为rate 的对象数组。每个 rate 对象中都有一个 tags 属性。我想将所有对象的标签组合到新数组中,这样预期的输出是:

["TAG_1_2_3_4", "TAG_7_8_9_0", "TAG_4_5_6"]

有没有比使用forEach 循环然后推送到数组更简单/更干净的方法?

例子:

[
  {
    "price": "123",
    "tags": [
      "TAG_1_2_3_4",
      "TAG_7_8_9_0"
    ]
  },
  {
    "price":"456",
    "tags":[
      "TAG_4_5_6"
    ]
  }
]

【问题讨论】:

  • 任何代码要显示?

标签: javascript arrays json object ecmascript-6


【解决方案1】:

使用Array.flatMap() 获取tags 并将它们展平为单个数组:

const arr = [{"price":"123","tags":["TAG_1_2_3_4","TAG_7_8_9_0"]},{"price":"456","tags":["TAG_4_5_6"]}]

const result = arr.flatMap(o => o.tags)

console.log(result)

如果不支持Array.flatMap(),您可以使用Array.reduce()Array.concat()

const arr = [{"price":"123","tags":["TAG_1_2_3_4","TAG_7_8_9_0"]},{"price":"456","tags":["TAG_4_5_6"]}]

const result = arr.reduce((acc, o) => acc.concat(o.tags), [])

console.log(result)

或者用Array.map()获取所有tags,然后通过展开到Array.concat()来展平:

const arr = [{"price":"123","tags":["TAG_1_2_3_4","TAG_7_8_9_0"]},{"price":"456","tags":["TAG_4_5_6"]}]

const result = [].concat(...arr.map(o => o.tags))

console.log(result)

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-14
  • 1970-01-01
  • 2017-11-08
  • 2021-03-22
相关资源
最近更新 更多