I am working on a function that will take an array of flattened nested objects and return another array, with the object attributes renamed.
For example, this input:
[
{ id: 13, student_name: 'John', parents.mother: 'Mia', parents.father: 'Milo', parents.mother.mother_education: 'msc', parents.father.father_education: 'bachelor', }, { id: 13, student_name: 'Erica', parents.mother: 'Lea', parents.father: 'Theo', parents.mother.mother_education: 'bachelor', parents.father.father_education: 'high school', }, ......]
should return:
[
{ id: 13, student_name: 'John', mother: 'Mia', father: 'Milo', mother_education: 'msc', father_education: 'bachelor', }, { id: 13, student_name: 'Erica', mother: 'Lea', father: 'Theo', mother_education: 'bachelor', father_education: 'high school', }, ......]
The code so far:
function format_object(myobj){
var raw_result = []; //the final variable - an array of objects
var raw_obj = {}; //every object is kept here temporarly
var depth = 0; //depth of the attribute name
for(var i = 0; i< myobj.length; i++){ //for each object
for(var attributename in myobj[i]){ //for each attribute
depth = attributename.split(".").length-1; //calculate name depth
if(depth == 0){
raw_obj[attributename] = myobj[i][attributename]; //for simple attribute names, just copy them on the temp object
}
else{
new_attribute = attributename.split('.')[depth] //for complex names, split last word
raw_obj[new_attribute] = myobj[i][attributename];
}
}
raw_result.push(raw_obj); //add the object we just created into the final variable
}
return raw_result;
}
Printing the raw_object I create, I get the correct object in each iteration. However , the final variable is composed of only the first object, repeated n times.