我将一个数组插入 for 循环。如何为相同的键添加值
{
"0156": {
"test": "hi"
}
},
{
"0156": {
"test": "hi2"
}
},
我想做这样的事情
{
"0156": {
"test": "hi"
"test": "hi2"
}
这是我尝试的
for(let i in test) {
let getTest = test[i];
const usr = getTest.id
var obj = {};
obj[usr] = {'test' : getTest.data};
getData.push(obj);
}
我尝试使用
if (typeof getData[0][usr] !== "undefined" ) {
}
但还是没成功。
最佳答案
您可以将值分组到数组中
const arr = [{
"0156": {
"test": "hi",
"test2": "abc"
}
},
{
"0156": {
"test": "hi2",
"test2": "abc1"
},
"0157": {
"test": "y1"
}
},
{
"0156": {
"test": "hi3"
},
"0158": {
"test": "ti2"
}
},
{
"0156": {
"test": "hi4"
},
"0157": {
"test": "y"
}
},
{
"0158": {
"test": "ti"
}
}
]
const res = arr.reduce(function(acc, curr) {
for (let p in curr) {
acc[p] = acc[p] || curr[p]
for (let p1 in curr[p])
acc[p][p1] = acc[p][p1] != curr[p][p1] ? [].concat(acc[p][p1], curr[p][p1]) : curr[p][p1]
}
return acc
}, {})
console.log(res)
关于javascript - 如何将值添加到数组中的重复键中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55574402/