javascript - 如何将值添加到数组中的重复键中

标签 javascript node.js

我将一个数组插入 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/

相关文章:

javascript - 动态生成的日历元素上的 jQuery 单击事件?

php - 如何使用jquery发送多个post请求?

node.js - 写入 MongoDB 时如何使用聚合和求和?

javascript - 如何使用强大的 npm 将文件上传到谷歌云

javascript - 从对象中提取单个键到数组

javascript - NodeJs : How to use a Promise across multiple files?

javascript - 访问键与热键

javascript - Reactjs,发送和读取变量

javascript - stackoverflow.com 使用哪个语法荧光笔插件? (Razor MVC 的语法高亮插件)

javascript - 如何使用 Express 和 Mongoose 发布和获取每个登录用户独有的数据?