Reputation: 2112
I want to append a list of object as
listObj = {1:{id:1,name:"fgh"}, 2:{id:2, name:ghj}}
to an array
arrayObj = {child:[
0:{id:3,name:fghj}
1:{id:9, name:cvbn}
]}
So final expected arrayObj should be
arrayObj = {child:[
0:{id:3,name:fghj}
1:{id:9, name:cvbn}
2:{id:1,name:"fgh"}
3:{id:2, name:ghj}
]}
I have tried append but it is not giving expected result
Upvotes: 0
Views: 59
Reputation: 10458
You can convert it into an array using
Object.keys(listObj).map(function (key) { return listObj[key]; });
let listObj = {1:{id:1,name:"fgh"}, 2:{id:2, name:'ghj'}};
// converts listObj into an array
var arr = Object.keys(listObj).map(function (key) { return listObj[key]; });
//console.log(arr);
arrayObj = {child:[
{id:3,name:'fghj'},
{id:9, name:'cvbn'}
]}
//just concat into the array now
arrayObj.child = arrayObj.child.concat(arr);
console.log(arrayObj);
Upvotes: 0
Reputation: 386560
You could get the values with Object.values
of the source object and push the items to the target array with spread syntax ...
.
var listObj = { 1: { id: 1, name: 'fgh' }, 2: { id: 2, name: 'ghj' } },
arrayObj = { child: [{ id: 3, name: 'fghj' }, { id: 9, name: 'cvbn' }] };
arrayObj.child.push(...Object.values(listObj));
console.log(arrayObj);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 1
Reputation: 68645
Get each property which are related to the current object via for in
loop, check if those are in the current object and push them into arrayObj.child
array.
var listObj = { 1: {id:1, name:"fgh"}, 2: {id:2, name:"ghj"}}
var arrayObj = {child:[
{id:3,name:"fghj"},
{id:9, name:"cvbn"}
]};
for(var prop in listObj){
if(listObj.hasOwnProperty(prop)) {
arrayObj.child.push(listObj[prop]);
}
}
console.log(arrayObj.child);
Or as @Nina suggests, via Object.values()
. Be attentive that here we use also ... spread
operator.
var listObj = { 1: {id:1, name:"fgh"}, 2: {id:2, name:"ghj"}}
var arrayObj = {child:[
{id:3,name:"fghj"},
{id:9, name:"cvbn"}
]};
arrayObj.child.push(...Object.values(listObj));
console.log(arrayObj.child);
Upvotes: 1