我正在开发一个函数,该函数将接受一个扁平嵌套对象数组并返回另一个数组,并重命名对象属性。
例如,这个输入:
[
{ 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', }, ......
]
应该返回:
[
{ 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', }, ......
]
到目前为止的代码:
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;
}
打印我创建的 raw_object,我在每次迭代中得到正确的对象。然而,最终变量仅由第一个对象组成,重复了 n 次。
最佳答案
在循环的每次迭代中都需要一个新的 raw_object
,否则您将不断更改同一对象的属性。
当您将对象推送到数组时,它推送的是一个引用,而不是副本。
所以你最终得到一个数组,其中每个元素都是对完全相同的单个对象的引用
var raw_result = []; //the final variable - an array of objects
var depth = 0; //depth of the attribute name
for(var i = 0; i< myobj.length; i++){ //for each object
var raw_obj = {}; // new object
.....
关于javascript - 重新创建对象数组的方法返回重复相同对象的相同数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42098266/