How can I add value into duplicate key in an arrays

时间:2019-04-08 13:17:45

标签: javascript node.js

I push an array in for loop. How can I add value into same keys

        {
            "0156": {
                "test": "hi"
            }
        },
        {
            "0156": {
                "test": "hi2"
            }
        },

I want to do something like this

            {
             "0156": {
                "test": "hi"
                "test": "hi2"
            }

Here Is what I try

for(let i in test) {
  let getTest = test[i];
  const usr = getTest.id
  var obj = {};
  obj[usr] = {'test' : getTest.data};
  getData.push(obj);
}

I try to use

if (typeof getData[0][usr] !== "undefined" ) {

 }

But still didn't work.

1 个答案:

答案 0 :(得分:2)

You can group the values in an array

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)