【问题标题】:Collecting the keys from array of objects and reducing it into a single array and removing duplicates从对象数组中收集键并将其减少为单个数组并删除重复项
【发布时间】:2019-05-23 12:21:24
【问题描述】:

我正在尝试提取数组中每个对象的键,然后我将收集所有键,然后连接小块键数组。然后我使用 set 消除重复并获取所有键。

我能够得到结果。有没有更好的方法来解决这个问题

任何帮助表示赞赏

let data = [
  {
    "test1": "123",
    "test2": "12345",
    "test3": "123456"
  },
  {
    "test1": "123",
    "test2": "12345",
    "test3": "123456"
  },
  {
    "test1": "123",
    "test2": "12345",
    "test3": "123456"
  },
  {
    "test1": "123",
    "test2": "12345",
    "test3": "123456"
  },
  {
    "test1": "123",
    "test2": "12345",
    "test3": "123456"
  },
]

let keysCollection = []

data.forEach(d => {
  let keys = Object.keys(d);
  keysCollection.push(keys)
})


let mergingKeysCollection = keysCollection.reduce((a,b) => [...a, ...b], [])

let uniqueKeys = new Set(mergingKeysCollection)

console.log('uniqueKeys', uniqueKeys)

【问题讨论】:

  • 你所做的实际上是有效的,只是集合没有字符串化..所以让你的工作只是做 -> let uniqueKeys = Array.from(new Set(mergingKeysCollection)) 甚至 let uniqueKeys = [...new Set(mergingKeysCollection))]
  • @Keith 或console.log('uniqueKeys', Array.from(uniqueKeys))

标签: javascript arrays


【解决方案1】:

您可以直接获取一个集合,而无需使用另一个键数组。

let data = [{ test1: "123", test2: "12345", test3: "123456" }, { test1: "123", test2: "12345", test3: "123456" }, { test1: "123", test2: "12345", test3: "123456" }, { test1: "123", test2: "12345", test3: "123456" }, { test1: "123", test2: "12345", test3: "123456" }],
    uniqueKeys = Array.from(
        data.reduce((r, o) => Object.keys(o).reduce((s, k) => s.add(k), r), new Set)
    );

console.log(uniqueKeys)

【讨论】:

    【解决方案2】:

    const data = [{"test1":"123","test2":"12345","test3":"123456"},{"test1":"123","test2":"12345","test3":"123456"},{"test1":"123","test2":"12345","test3":"123456"},{"test1":"123","test2":"12345","test3":"123456"},{"test1":"123","test2":"12345","test3":"123456"},];
    
    const res = data.reduce((unique, item) => (Object.keys(item).forEach(key => unique.add(key)), unique), new Set);
    
    console.log([...res]);
    .as-console-wrapper {min-height: 100%}

    【讨论】:

      猜你喜欢
      • 2020-04-28
      • 1970-01-01
      • 1970-01-01
      • 2021-05-12
      • 2018-09-11
      • 1970-01-01
      • 2017-08-17
      • 2018-12-22
      • 2021-11-25
      相关资源
      最近更新 更多