最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

object - How to merge with nested key in javascript spread operator? - Stack Overflow

programmeradmin2浏览0评论

I have the following objects like

obj1 = { key1: { a: 1}}

I want to merge the following object with the above

key1 = { b: 2}

I want to get the result as following by merging the key1 with the existing key in the first object.

{key1: {a: 1, b: 2}} 

How can I do this using spread operator in javascript? Thanks in advance.

I have the following objects like

obj1 = { key1: { a: 1}}

I want to merge the following object with the above

key1 = { b: 2}

I want to get the result as following by merging the key1 with the existing key in the first object.

{key1: {a: 1, b: 2}} 

How can I do this using spread operator in javascript? Thanks in advance.

Share Improve this question edited May 10, 2019 at 11:15 Jack Bashford 44.2k11 gold badges55 silver badges82 bronze badges asked May 10, 2019 at 11:12 HareeshHareesh 1,5874 gold badges21 silver badges48 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 8

You can spread both existing and new object

Note: Using spread operator will only merge the enumerable properties.

const obj1 = { key1: { a: 1}}
const key1 = { b: 2};
const res = {...obj1,key1:{...obj1.key1,...key1}};
console.log(res)

If you want to modify the original object then only change obj.key1

const obj1 = { key1: { a: 1}}
const key1 = { b: 2};
obj1.key1 = {...obj1.key1,...key1}
console.log(obj1)

Just use the spread operator like so:

let obj1 = {
  key1: {
    a: 1
  }
};

let key1 = {
  b: 2
};

obj1.key1 = { ...obj1.key1, ...key1 };
console.log(obj1);
.as-console-wrapper { max-height: 100% !important; top: auto; }

You could splead it into the wanted property.

var obj1 = { key1: { a: 1 } },
    key1 = { b: 2 };
    
obj1.key1 = { ...obj1.key1, ...key1 };

console.log(obj1);

Try this:

let obj1 = { key1: { a: 1}}

let b = { b: 2}
let a = obj1.key1; //{a:1}

// merge using spread operator
let key1 = {...a, ...b}; //{a:1, b:2}

obj1.key1 = key1; //{"a":1,"b":2"}

console.log(obj1) //{ "key1":{"a":1,"b":2"}}

You should use Object.assign

var obj1 = { key1: { a: 1}};
var key1 = { b: 2};

Object.assign(obj1.key1, key1);

console.log(obj1)

发布评论

评论列表(0)

  1. 暂无评论