当键是动态的时,从对象数组中获取唯一的对象

时间:2019-10-23 11:48:59

标签: javascript arrays unique

这里是带有动态键的对象数组:

[ { 'CF Bangalore': 1 },
  { 'CF Bangalore': 2 },
  { 'CF Dhanbad': 3 },
  { 'CF Bangalore': 0 },
  { 'CF Kundli': 4 },
  { 'CF Pollachi': 1 },
  { 'CF Delhi': 2 },
  { 'CF Bangalore': 0 },
  { 'CF Bangalore': 6 },
  { 'CF Bangalore': 3 },
  { 'CF Pollachi': 2 },
  { 'CF Kundli': 9 },
]

我想获得唯一的对象。我试过使用Set和Map。但是这里的键是唯一的。 所需的输出:[{'CF Bangalore':12},{'CF Kundli':13},{'CF Pollachi':3}, {'CF Dhanbad':3},{'CF Delhi':2}]

2 个答案:

答案 0 :(得分:0)

通过将数组扩展到Object.assign()合并对象-这将使所有属性唯一。然后获取条目,并映射回对象数组。

const arr = [{"CF Bangalore":""},{"CF Bangalore":""},{"CF Dhanbad":""},{"CF Bangalore":""},{"CF Kundli":""},{"CF Pollachi":""},{"CF Delhi":""},{"CF Bangalore":""},{"CF Bangalore":""},{"CF Bangalore":""},{"CF Pollachi":""},{"CF Kundli":""}]

const result = Object.entries(Object.assign({}, ...arr)) // merge the objects an get an array of [key, value] pairs
  .map(([key, value]) => ({ [key]: value })) // map back to an array of objects
  
console.log(result)

答案 1 :(得分:0)

您需要使用Object.keys来获取键,假设每个对象的元素中只有1个键,则您可以访问第0个索引值

let arr = [ { 'CF Bangalore': '' },{ 'CF Bangalore': '' },{ 'CF Dhanbad': '' },{ 'CF Bangalore': '' },{ 'CF Kundli': '' },{ 'CF Pollachi': '' },{ 'CF Delhi': '' },{ 'CF Bangalore': '' },{ 'CF Bangalore': '' },{ 'CF Bangalore': '' },{ 'CF Pollachi': '' },{ 'CF Kundli': '' },]

let uniq = [...new Set(arr.map(x => Object.keys(x)[0]))]

console.log(uniq)


  

我可以获取键的总值吗?

let arr = [{ 'CF Bangalore': 1 },{ 'CF Bangalore': 2 },{ 'CF Dhanbad': 3 },{ 'CF Bangalore': 0 },{ 'CF Kundli': 4 },{ 'CF Pollachi': 1 },{ 'CF Delhi': 2 },{ 'CF Bangalore': 0 },{ 'CF Bangalore': 6 },{ 'CF Bangalore': 3 },{ 'CF Pollachi': 2 },{ 'CF Kundli': 9 },]

let uniq = arr.reduce((op, inp) => {
  let [key, value] = Object.entries(inp)[0]
  if (op.has(key)) {
    op.get(key)[key] += value
  } else {
    op.set(key, inp)
  }
  return op
}, new Map())

console.log([...uniq.values()])