This question already has answers here:
Merge specific properties of objects together with JavaScript
                                
                                    (3个答案)
                                
                        
                2个月前关闭。
            
        

我想知道如果在JavaScript中使用相同的id,则如何组合数组值。

我尝试下面的代码

let result = this.getData(obj);

function getData(obj) {
 return obj.map(e=>({procode: e.prcode, id: e.id});
}



var obj= [
  {
    id: "1",
    prcode: "dessert"
  },{
    id: "1",
    prcode: "snacks"
  }, {
   id: "2",
   prcode: "cafe"
 }, {
  id: "4",
  prcode: "all"
}
]



预期产量:

result = [
 {id: "1", prcode: "dessert,snacks"},
 {id: "2", prcode: "cafe"},
 {id: "4", prcode: "all"}
]

最佳答案

您可以在reduce旁边使用Object.values()



var obj = [
  { id: "1", prcode: "dessert" },
  { id: "1", prcode: "snacks" },
  { id: "2", prcode: "cafe" },
  { id: "4", prcode: "all" }
]

const out = obj.reduce((a, v) => {
  if(a[v.id]) {
    a[v.id].prcode = [a[v.id].prcode, v.prcode].join(',')
  } else {
    a[v.id] = v
  }
  return a
}, {})
console.log(Object.values(out))

09-10 04:53
查看更多