我正在尝试以递归方式从旧对象构建一个新对象,如:
var arr = {};
var markCheckBoxes = function(obj){
var trackArr = new Array();
for(var prop in obj){
if(!!obj[i] && typeof(obj[i])=="object"){
trackArr.push(i);
markCheckBoxes(obj[i]);
trackArr.pop();
}
else{
var str = trackArr.join(".") + "." + i;
arr[str] = true;
}
}
};
但是这会创建一个扁平的对象。例如,如果obj
是:
obj = {
prop1: {
subprop1: "text",
subprop2: "extra"
}, prop2:{
subprop: {another: 3}
}
}
然后上面的函数用键创建一个对象:
{
"prop1.subprop1": true,
"prop1.subprop2": true,
"prop2.subprop.another": true
}
答案 0 :(得分:2)
假设OP想要为密钥的true
值创建对象的其他副本,您可以修改代码如下
var makeChecks = function(obj){
var cloneTo = {};
for(var prop in obj){
if(obj.hasOwnProperty(prop) && typeof(obj[prop]) === 'object'){
cloneTo[prop] = makeChecks(obj[prop]);
}
else{
cloneTo[prop] = true;
}
}
return cloneTo;
}
var obj = {
prop1: {
subprop1: "text",
subprop2: "extra"
}, prop2:{
subprop: {another: 3}
}
}
var output = makeChecks(obj);
console.log(output)
/*
{
"prop1": {
"subprop1": true,
"subprop2": true
},
"prop2": {
"subprop": {
"another": true
}
}
}
*/