javascript - 如何动态地为对象的相同属性赋值?

标签 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}
}

最佳答案

为此,您可以在循环中使用 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;
}

关于javascript - 如何动态地为对象的相同属性赋值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47620082/

相关文章:

javascript - 我可以制作一个共享的reactjs验证组件吗?

javascript - 如何在 javascript 中处理可能的 HTML 编码值

javascript - 在 JavaScript 中,当完成通过 new ActiveXObject 创建的对象时,是否需要将其设置为 null?

javascript - 日期在 IE 中显示为 NaN?

javascript - Firefox PDF 查看器事件

javascript - 解决点击事件问题

javascript - 为什么 `([' 1',' 2',' 3']).map(parseInt)` 无法得到正确的结果?

javascript - 如何在gsp上显示下拉列表的选定值

javascript - 重新渲染我的 React 组件时我的动画不工作?

javascript - 如何使我的 html 代码中的链接可点击?