简体   繁体   中英

node Object.assign(obj1,obj2,obj3) returning the json properties of obj3

I have some encapsulated mongoose queries to a mongodb.

collection1.findOne({ parm: value}, function(err, item){
    var a = item.a;
    var b = item.b;
    collection2.findOne({parm1: a}, function(err, item2){
        collection3.findOne({parm2: b}, function(err, item3){
            var records = Object.assign(item, item2, item3);
        });
    });
});

If I print item, item2 and item3 before the assign all objects print different as well as some equal properties. When I print records after the var records line it only shows up item3 json properties.

Per the documentation it should

copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

Which is not happening. Am I doing something wrong or is this the expected behavior?

I require async library. Is it possible that imports might be altering the behavior of object.assign?

When I print records after the var records line it only shows up item3 json properties.

As per spec

iii) if desc is not undefined and desc.[[Enumerable]] is true, then

a) Let propValue be Get(from, nextKey).

b) ReturnIfAbrupt(propValue).

c) Let status be Set(to, nextKey, propValue, true). //observe this line

d) ReturnIfAbrupt(status).

So, this is an expected behavior since assign works by

  • Assigning values from left source onwards to right .
  • And doesn't check if a property has already been set .

Demo

 var a = {a:1, b:2}; var b = {b:3, c:4}; var c = Object.assign( {}, a,b ); console.log(c); 

Observe that the output overrides b property

{ "a": 1, "b": 3, "c": 4 }

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