Kranthi Sama Kranthi Sama - 16 days ago 6
Javascript Question

Combine different JavaScript objects in one object

I have four different JavaScript objects. I want to send all these four objects as one to my view layer.

Here is the code:

var pending=[];
var approved=[];
for (var key in rdata) {
if (rdata.hasOwnProperty(key)) {
var obj = rdata[key];
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
if(obj[prop].statusEnum=="PENDING"){
pending.push(obj[prop]);
}else if(obj[prop].statusEnum=="APPROVED"){
approved.push(obj[prop]);
}
}
}
}
}


So here I got two objects "pending" and "approved" which I want to wrap into one single object separately with some keys to the view layer, so that I can use it at different places.

Answer

You can easily just create a single object with two lists 'pending' and 'approved', javascript is excellent for using and manipulating objects, it is good to take advantage of that

var list = {'pending':[], 'approved':[]}

then in your for in loop you can do:

list['pending'].push(obj[prop])

and

list['approved'].push(obj[prop])