user172902 user172902 - 4 years ago 208
Javascript Question

Process Javascript Object with random Keys

After I download my data from firebase, the returned object is an object with several child objects.

myObj =
{
"J251525" : {
"email" : "TOM@MAIL.COM",
"description" : "CLEAN THE HOUSE",
"refNumber" : "J251525"
},
"J512912" : {
"email" : "JAMES@MAIL.COM",
"description " : "BRUSH HORSE",
"refNumber" : "J512912"
},
"J53f512" : {
"email" : "HARRY@MAIL.COM",
"description " : "WASH CAR",
"refNumber" : "J53f512"
}
};


I want to breakdown this data so that I can use it to display in my thead/tbody in html similar to the following layout

screen shot

So I need to


  1. Somehow create an array of ['email', 'description', 'refNumber'] from looking at myObj.

  2. Loop through the object (Is that possible with object?) and create several arrays like




['TOM@MAIL.COM','CLEAN THE HOUSE', 'J251525']

['JAMES@MAIL.COM','BRUSH HORSE', 'J512912']

['HARRY@MAIL.COM','WASH CAR', 'J53f512']


I dont know where to start for this because normally when I deal with objects, I know the key and I didnt have to loop through anything. However in this case, I have to somehow find how many objects is inside this main object.
Also, I can not do things like myObj['J251525'] because I would not know anthing about the key J251525

Note that I am using typescript with angular 2.

Answer Source

To convert the object to your required format you can use this:

var myObj = 
{
    "J251525" : {
        "email" : "TOM@MAIL.COM",
        "description" : "CLEAN THE HOUSE",
        "refNumber" : "J251525"
    },
    "J512912" : {
        "email" : "JAMES@MAIL.COM",
        "description" : "BRUSH HORSE",
        "refNumber" : "J512912"
    },
    "J53f512" : {
        "email" : "HARRY@MAIL.COM",
        "description" : "WASH CAR",
        "refNumber" : "J53f512"
    }
};

var result = Object.keys(myObj).map(function(key) {
  return [myObj[key].email, myObj[key].description, key];
});

console.log(result);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download