首页 > 解决方案 > Add multiple properties at once, to object which already has some properties defined

问题描述

Is it possible to add multiple properties at once without overwriting the properties which are already inside object?

object = {prop1: "1", prop1: "2", prop3: "3"};
//Want to add: {prop4: "4", prop5: "5", prop6: "6"} 

Is there any way to do this without iterating over the properties I want to add and adding one by one?

标签: javascript

解决方案


Use Object assign

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

object = {prop1: "1", prop1: "2", prop3: "3"};
//Want to add: {prop4: "4", prop5: "5", prop6: "6"} 

Object.assign(object, {prop4: "4", prop5: "5", prop6: "6"})
console.log(object)


推荐阅读