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....