How to click elements of an object to another object?

As in arrays, we can add new elements using the .push(item) array. How to do the same with objects ? And can this be done inside the object? For instance:

 var myObject={apple: "a", orange: "o"}; var anothObject = {lemon: "l", myObject}; 
+6
source share
6 answers

You can use the jQuery extension function: http://api.jquery.com/jquery.extend/

 var object1 = { apple: 0, banana: { weight: 52, price: 100 }, cherry: 97 }; var object2 = { banana: { price: 200 }, durian: 100 }; // Merge object2 into object1 $.extend( object1, object2 ); 
+2
source

You can add some object properties just like this:

 obj = {a : "1", b : "2"}; myObj = {c: "3", d : "4"}; myObj.a = obj.a; myObj.b = obj.b; 

Update

In this case, simply do the following:

 for(var prop in obj) myObj[prop] = obj[prop]; 

And to filter out unwanted properties inside the loop body, you can also do this:

 for (var prop in obj) { if (obj.hasOwnProperty(prop)) { myObj[prop] = obj[prop]; } } 
+3
source

To copy all elements of one object to another object, use Object.assign :

 var myObject = { apple: "a", orange: "o" }; var anothObject = Object.assign( { lemon: "l" }, myObject ); 

Or a more elegant ES6 style using a distributor ... :

 var myObject = { apple: "a", orange: "o" }; var anothObject = { lemon: "l", ...myObject }; 

Please note that although I am writing this, it is still in the application stage, although support is fairly widespread (it works in my browser).

+1
source
 var myObject={apple: "a", orange: "o"}; myObject.lemon = 1; // myObject is now {apple: "a", orange: "o", lemon: 1} 
0
source

You can use jQuery.extend() function

 var myObject={apple: "a", orange: "o"}; var anothObject = {lemon: "l"}; jQuery.extend(myObject, anothObject); console.log(myObject); 
0
source

Parameter without jquery: you can iterate the keys of the object to be combined.

 var myObject={apple: "a", orange: "o"}; var anothObject = {lemon: "l"}; Object.keys(myObject).forEach(function(key) { anothObject[key] = myObject[key]; }); 

At the end of the anothObject loop anothObject is {lemon: "l", apple: "a", orange: "o"}

0
source

Source: https://habr.com/ru/post/986245/


All Articles