简体   繁体   中英

JSON.stringify inside Object.assign creates multiply properties

JSON stringify add additional properties to object when I use it with Object.assign.

Could you please explain me, why this happens and how to avoid it?

Example: https://jsbin.com/mikokomibu/edit?js,console

//////////////////Example without JSON////////////////////
let object = {}
object = Object.assign({}, object, object[1]=2);
console.log(object)
/////////////////////////////////////////////////////////
Output:
[object Object] {
1: 2
}

//////////////////Example with JSON/////////////////////
let objectNew = {}
let first = JSON.stringify(1);
let second = JSON.stringify(2);
objectNew  = Object.assign({}, objectNew , objectNew[first]=second);
console.log(objectNew);
/////////////////////////////////////////////////////////
Output:
[object Object] {
0: "2",
1: "2"
}

When Object.assign encounters an iterable, it treats it as an array and assigns numeric properties to the target object:

 x = Object.assign({}, 'abc') console.log(x) 

Your first snippet is the same as this:

target = Object.assign({}, {1:2}, 2);

assign copies object to the target, and skips 2 , because it's a primitive.

The second snippet is like this:

target = Object.assign({}, {1:"2"}, "2");

here, assign copies object to the target, and processes "2" , which is an iterable, and equivalent to {0:"2"} , according to the above. So, the snippet turns into this

target = Object.assign({}, {1:"2"}, {0:"2"});

which explains your result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM