我需要一种有效的方法来遍历对象文字数组,并将具有重复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"
]}
答案 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
这样的对象。然后级联这些number
当id
已经存在于accumulator
,否则添加新的密钥到蓄能器。
{
"101": {
"id": 101,
"name": "Bubbles' Cat Farm",
"number": "123, 789"
}
}
然后使用Object.values
仅获取数组中theList
的值。
答案 2 :(得分:1)
您可以将容器作为字典,其中的键是ID,每个值是一个空列表。所以,当你通过原始数据循环。如果密钥犯规存在,创建一个项目的列表。如果该键确实已经存在,只需将值添加到列表中即可。
答案 3 :(得分:1)
使用reduce
和findIndex
函数,您将能够实现所需的功能。
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)