I have two JSON objects that I want to create one object out of, with either Angular or plain JavaScript (no jQuery). Angular.extend didn't seem to get me what I wanted, and instead did more of a merge.
{
"field1-1": 1,
"field1-2": 2,
"field1-3": 3,
"field1-4": "four",
"field1-5":
{
"field1-1-1": 5.1,
"field1-1-2": 5.2
}
}
And
{
"field2-1": 21,
"field2-2": 22,
"field2-3": "three",
"field2-4":
{
"field2-1-1": 4.1,
"field2-1-2": 4.2
}
}
I want the end result to be:
{
"field1-1": 1,
"field1-2": 2,
"field1-3": 3,
"field1-4": "four",
"field1-5":
{
"field1-1-1": 5.1,
"field1-1-2": 5.2
}
},
{
"field2-1": 21,
"field2-2": 22,
"field2-3": "three",
"field2-4":
{
"field2-1-1": 4.1,
"field2-1-2": 4.2
}
}
So you want an array:
var array = [object1, object2];
var object1 = { "field1-1": 1, "field1-2": 2, "field1-3": 3, "field1-4": "four", "field1-5": { "field1-1-1": 5.1, "field1-1-2": 5.2 } },
object2 = { "field2-1": 21, "field2-2": 22, "field2-3": "three", "field2-4": { "field2-1-1": 4.1, "field2-1-2": 4.2 } },
array = [object1, object2];
document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');
If you like to get a single object, then you can use this proposal.
It iterates over the array with the objects and then over the keys of an object. The values from the original object are assigned to the corresponding property of the new object.
var object1 = { "field1-1": 1, "field1-2": 2, "field1-3": 3, "field1-4": "four", "field1-5": { "field1-1-1": 5.1, "field1-1-2": 5.2 } },
object2 = { "field2-1": 21, "field2-2": 22, "field2-3": "three", "field2-4": { "field2-1-1": 4.1, "field2-1-2": 4.2 } },
object = function (array) {
var o = {};
array.forEach(function (a) {
Object.keys(a).forEach(function (k) {
o[k] = a[k];
});
});
return o;
}([object1, object2]);
document.write('<pre>' + JSON.stringify(object, 0, 4) + '</pre>');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With