如何遍历对象文字数组,并串联共享重复ID的值?

时间:2019-02-01 19:02:01

标签: javascript arrays javascript-objects

我需要一种有效的方法来遍历对象文字数组,并将具有重复ID的对象中的值连接起来。

与将多个for循环嵌套在一起相比,有没有更优雅的方法?

例如,这是我得到的数据:

{ "theList": [
    {
        "id": 101,
        "name": "Bubbles' Cat Farm",
        "number": "123"
    },
    {
        "id": 102,
        "name": "Sunnyvale Park",
        "number": "456"
    },
    {
        "id": 101,
        "name": "Bubbles' Cat Farm",
        "number": "789"
]};

预期结果应该是:

{ "theList": [
    {
        "id": 101,
        "name": "Bubbles' Cat Farm",
        "number": "123, 789"
    }, 
    {
        "id": 102,
        "name": "Sunnyvale Park",
        "number": "456"
]}


4 个答案:

答案 0 :(得分:3)

您可以使用reduce

let obj = [{ "id": 101,"name": "Bubbles' Cat Farm","number": "123"},{"id": 102,"name": "Sunnyvale Park","number": "456"},{"id": 101,"name": "Bubbles' Cat Farm","number": "789"}];

let op = obj.reduce((out,inp)=>{
  if(out[inp.id]){
    out[inp.id].number += ', ' + inp.number;
  } else {
    out[inp.id] = inp
  }
  return out
},{})

console.log(Object.values(op))

答案 1 :(得分:2)

如果number是具有不同值的唯一键,则可以使用这样做reduce

const input = {"theList":[{"id":101,"name":"Bubbles' Cat Farm","number":"123"},{"id":102,"name":"Sunnyvale Park","number":"456"},{"id":101,"name":"Bubbles' Cat Farm","number":"789"}]}

const merged = input.theList.reduce((acc, {id,name,number}) =>{
  acc[id] 
    ? acc[id]["number"] += ", " + number 
    : acc[id] = {id,name,number};
    
  return acc
},{})

const final = { "theList": Object.values(merged) }
console.log(final)

创建与每个独特的累加器id如键和你的最后阵列中需要为value这样的对象。然后级联这些numberid已经存在于accumulator,否则添加新的密钥到蓄能器。

{
  "101": {
    "id": 101,
    "name": "Bubbles' Cat Farm",
    "number": "123, 789"
  }
}

然后使用Object.values仅获取数组中theList的值。

答案 2 :(得分:1)

您可以将容器作为字典,其中的键是ID,每个值是一个空列表。所以,当你通过原始数据循环。如果密钥犯规存在,创建一个项目的列表。如果该键确实已经存在,只需将值添加到列表中即可。

答案 3 :(得分:1)

使用reducefindIndex函数,您将能够实现所需的功能。

const array = [{
    "id": 101,
    "name": "Bubbles' Cat Farm",
    "number": "123"
  },
  {
    "id": 102,
    "name": "Sunnyvale Park",
    "number": "456"
  },
  {
    "id": 101,
    "name": "Bubbles' Cat Farm",
    "number": "789"
  }
]

const result = array.reduce((accum, cv) => {
  const index = accum.findIndex(item => item.id === cv.id);
  if (index === -1) {
    accum.push(cv);
  } else {
    accum[index].number += ", " + cv.number;
  }
  return accum;
}, [])

console.log(result)