Brian Powell Brian Powell -4 years ago 86
Javascript Question

Javascript write new object based on the keys and values of another object

I have a large object, and not each element within the object has the same keys or number of keys. The first element has all the keys, and this first element's values are what I want to actually USE as the keys for each element, filling in with blanks where the element does not have this key.

I can wrap my brain around WHAT needs to happen, but I just can't figure out how to code it. This is the sample as I import it:

[
{
"A": "Name",
"B": "Type",
"C": "Company",
"D": "Year",
"E": "Alt1",
"F": "Name1",
"G": "Alt2",
"H": "Name2",
"I": "Notes"
},
{
"A": "Skittles",
"C": "Mars",
"D": 0,
"E": "Cadbury",
"F": "Sour Patch Kids",
"I": "CLEAN"
},
{
"A": "Love",
"B": "Chocolate",
"C": "Dove",
"D": 0,
"E": "0",
"F": "0",
}
]


In this example, the second element is missing keys "B", "G", and "H", while the third element is missing keys "G", "H" and "I". So using the FIRST element's keys
A through I
as a master template, I want to rewrite a new object, that looks like this:

[
{
"Name": "Skittles",
"Type": "",
"Company": "Mars",
"Year": 0,
"Alt1": "Cadbury",
"Name1": "Sour Patch Kids",
"Alt2": "",
"Name2": "",
"Notes": "CLEAN"
},
{
"Name": "Love",
"Type" : "Chocolate",
"Company": "Dove",
"Year": 0,
"Alt1": "",
"Name1": "",
"Alt2": "",
"Name2": "",
"Notes": ""
}
]


I've written several
for
loops but I cannot seem to grasp the complexity of this... This is as far as I've gotten:

a = [];
b = [];
new_keys = [];

/* Capture the new keys */
for(var v in user_file[0]) {
if(user_file[0].hasOwnProperty(v)) {
new_keys.push(user_file[0][v]);
}
}

/* user_file is the object I pasted above... */
for ( var i = 0 ; i<user_file.length; i++ ) {
/* write the b object */

/* then push that object into a */
a.push(b);

/* Empty out b */
b = [];
}


I have no idea how to write this
b[]
object....

Answer Source

You could iterate only the elements from index 1 and greater and take the object at index zero as blue print for the objects.

var data = [{ A: "Name", B: "Type", C: "Company", D: "Year", E: "Alt1", F: "Name1", G: "Alt2", H: "Name2", I: "Notes" }, { A: "Skittles", C: "Mars", D: 0, E: "Cadbury", F: "Sour Patch Kids", I: "CLEAN" }, { A: "Love", B: "Chocolate", C: "Dove", D: 0, E: "0", F: "0", }],
    keys = Object.keys(data[0]),
    result = data.slice(1).map(function (o) {
        var temp = {};
        keys.forEach(function (k) {
            temp[data[0][k]] = k in o ? o[k] : '';
        });
        return temp;
    });

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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