为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

一只萌萌小番薯 2021-04-07 16:15:53
我将数组推入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" ) { }但是还是没用。
查看完整描述

1 回答

?
哔哔one

TA贡献1854条经验 获得超8个赞

您可以将值分组到一个数组中


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)


查看完整回答
反对 回复 2021-04-22
  • 1 回答
  • 0 关注
  • 156 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信