Angularjs Join Two Objects
I have two objects: obj1 = { 'id1': 1, 'name1': 'anyone1', 'birth1': 22, 'year1': 1993 }; obj2 = { 'id2': 1, 'name2': 'anyone', 'birth2': 22, 'year2': 1993 }; And I would like t
Solution 1:
The solution is to create a new object
with two keys
:
obj1 = { 'id1': 1, 'name1': 'anyone1', 'birth1': 22, 'year1': 1993 };
obj2 = { 'id2': 1, 'name2': 'anyone', 'birth2': 22, 'year2': 1993 };
var obj={};
obj["obj1"]=obj1;
obj["obj2"]=obj2;
console.log(obj);
console.log(obj.obj1.id1);
Solution 2:
Another example using Object.assign
:
obj1 = { 'id1': 1, 'name1': 'anyone1', 'birth1': 22, 'year1': 1993 };
obj2 = { 'id2': 1, 'name2': 'anyone', 'birth2': 22, 'year2': 1993 };
var obj3 = Object.assign({}, { obj1: obj1 }, { obj2: obj2} );
console.log(obj3);
Solution 3:
Also, since it was an angular question, you can also use the angular.extend
function:
var obj1 = { 'id1': 1, 'name1': 'anyone1', 'birth1': 22, 'year1': 1993 };
var obj2 = { 'id2': 1, 'name2': 'anyone', 'birth2': 22, 'year2': 1993 };
var obj3 = angular.extend({}, { obj1: obj1, obj2: obj2 } );
console.log(obj3);
<scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
Solution 4:
Use
var myNamedStuff = new Map;
myNamedStuff.set("obj1", obj1);
etc.
What you're asking for is a Map
. We used plain objects as maps before ES6, but we got all sorts of security risks and exceptions related to name clashes, especially when vendor-specific properties show up in Object.prototype
. ES6 introduces the Map
so that we never do that again and instead have a guaranteed clean name space like we really wanted.
Post a Comment for "Angularjs Join Two Objects"