在对象数组中将对象与对象合并

时间:2018-07-04 17:14:37

标签: javascript javascript-objects

我有一系列看起来像

的对象
{  
   "foo":[  
      {  
         "bar":"boo"
      },
      {  
         "baz":"bang"
      }
   ]
}

我想用一个新值更新baz,但是我不知道如何合并这两个对象?

我尝试了类似Object.assign({}, foo,{baz: 'beep'})

的操作

但这没用吗?

3 个答案:

答案 0 :(得分:0)

如果您尝试创建foo的修改后的副本,请使用Array.prototype.map

const foo = [  
  {  
     "bar":"boo"
  },
  {  
     "baz":"bang"
  }
];

const newFoo = foo.map(value => {
  if('baz' in value) return Object.assign({}, value, {a: 'b'});
  return value;
});

console.log(newFoo);

答案 1 :(得分:0)

假设您不一定知道要修改的元素的数组索引,则需要搜索该数组以找到它-例如,使用Array.find()

let quux = {  
   "foo":[  
      {  
         "bar":"boo"
      },
      {  
         "baz":"bang"
      }
   ]
}

quux.foo.find(
  (obj) => {
    return obj.baz === "bang"
  }
).baz="beep";

console.log(quux);
// This mutates the original object; if you need a clone wrap this in an Object.assign as shown in other answers

(出于这个原因,对象数组可能会很不方便;使用对象对象可能会更好,因此每个对象都有一个ID。)

答案 2 :(得分:0)

foo is an Array of objects to replace it with new value, try the following:

var obj =  { "foo":[ { "bar":"boo" }, { "baz":"bang" } ] };
var index = obj.foo.findIndex((o) =>Object.keys(o).includes("baz"));
if(index != -1)
  Object.assign(obj.foo[index], {baz: 'beep'});
  
  console.log(obj);

相关问题