如何动态地将值赋给对象的相同属性?

时间:2017-12-03 15:46:28

标签: javascript

我们说我有一个数组:

var myArr = [
    {a: {'one': 1} },
    {b: {'two': 2} },
    {a: {'three': 3} },
    {c: {'four': 4} },
    {d: {'five': 5} }
];

我想创建一个对象说:

let myObj = {};
myObj = {
    a: {
        'one': 1,
        'three': 3
    },
    b: {'two': 2},
    c: {'four': 4},
    d: {'five': 5}
}

属性'a'被覆盖。如何防止这种情况发生?

我面临的问题是如果我执行以下操作:

myArr.forEach((x) => {
    myObj[Object.keys(x)[0]] = x[Object.keys(x)];
});

我得到了结果:

{ 
    "a": {"three": 3},
    "b": {"two": 2},
    "c": {"four": 4}, 
    "d": {"five": 5}
}

2 个答案:

答案 0 :(得分:2)

您可以在循环中使用Object.assign,请参阅评论:



var myArr = [
  {a : {'one':1}},
  {b: {'two':2}},
  {a : {'three':3}},
  {c : {'four':4}},
  {d:{'five':5}}
];

let myObj = {};
myArr.forEach(entry => {
  // Get the first key in the object
  const key = Object.keys(entry)[0];
  // Merge the object in `myObj[key]` with the one in `entry[key]`; it's okay
  // if there's no `myObj[key]`, `Object.assign` will skip over `undefined`
  myObj[key] = Object.assign({}, myObj[key], entry[key]);
});
console.log(myObj);

.as-console-wrapper {
  max-height: 100% !important;
}




这不是超高效的,它会不必要地重新创建对象,但除非你在成千上万个对象的紧密循环中这样做,否则它并不重要。如果你是,我们只是分支迭代器回调:



var myArr = [
  {a : {'one':1}},
  {b: {'two':2}},
  {a : {'three':3}},
  {c : {'four':4}},
  {d:{'five':5}}
];

let myObj = {};
myArr.forEach(entry => {
  // Get the first key in the object
  const key = Object.keys(entry)[0];
  const src = entry[key];
  const dest = myObj[key];
  if (!dest) {
    // Create a copy of the object and remember it
    myObj[key] = Object.assign({}, src);
  } else {
    // Copy properties from the source to the existing target
    Object.keys(src).forEach(k => {
      dest[k] = src[k];
    });
  }
});
console.log(myObj);

.as-console-wrapper {
  max-height: 100% !important;
}




答案 1 :(得分:1)

您可以使用reduce之类的:

var myArr = [ {a: {'one': 1} }, {b: {'two': 2} }, {a: {'three': 3} }, {c: {'four': 4} }, {d: {'five': 5} } ];

var myObj = myArr.reduce(function(obj, o) {       // for each object o in the array myArr
  var key = Object.keys(o)[0];                    // get the key of the object o ('a', 'b', ...)
  var subKey = Object.keys(o[key])[0];            // get the key of the object inside o ('one', 'two', ...)
  if(!obj[key]) {                                 // if there is no object for the key 'key' in the result object
    obj[key] = {};                                // then add one
  }
  obj[key][subKey] = o[key][subKey];              // then add an entry for the 'subKey' to the object under the key 'key' (with the value taken from o)
  return obj;
}, {});

console.log(myObj);