javascript - Merge two objects but only existing properties -


i have 2 objects. , want merge 2 objects property value present first object.

   obj1 : {         "name": "",         "age": ""    }    obj2 : {         "name": "leo",         "age": "14",         "company": "aero",         "shift": "night"   } 

the output want is:

  obj1 : {         "name": "leo",         "age": "14"    } 

the company , shift no need merge because 2 property not present in obj1.

the code i've done far is: object.assign({}, obj1, obj2);

but it's not give me right output. gives is:

 merge : {         "name": "leo",         "age": "14",         "company": "aero",         "shift": "night"   } 

could me how achieve output this:

  merge : {         "name": "leo",         "age": "14",   } 

many thanks!

assuming want enumerable properties, done object.keys , in (or hasownproperty):

object.keys(obj2).foreach(function(key) {     if (key in obj1) { // or obj1.hasownproperty(key)         obj1[key] = obj2[key];     } }); 

example:

var obj1 = {    "name": "",    "age": ""  };    var obj2 = {    "name": "leo",    "age": "14",    "company": "aero",    "shift": "night"  };    object.keys(obj2).foreach(function(key) {    if (key in obj1) { // or obj1.hasownproperty(key)      obj1[key] = obj2[key];    }  });  console.log(obj1);

or in es2015 syntax (since mentioned object.assign), although doesn't change in case:

object.keys(obj2).foreach(key => {     if (key in obj1) { // or obj1.hasownproperty(key)         obj1[key] = obj2[key];     } }); 

or more fluent approach, revisits keys in obj1 (not it's matter:

object.keys(obj2).filter(key => key in obj1).foreach(key => {     obj1[key] = obj2[key]; }); 

since foreach ignores return value of callback, go further in concise-land:

object.keys(obj2).filter(key => key in obj1).foreach(key => obj1[key] = obj2[key]); 

Comments

Popular posts from this blog

php - How to display all orders for a single product showing the most recent first? Woocommerce -

asp.net - How to correctly use QUERY_STRING in ISAPI rewrite? -

angularjs - How restrict admin panel using in backend laravel and admin panel on angular? -