我想编写一个函数,它将JavaScript对象作为输入,具有对象的选定属性,并返回修改后的缩进/分组结构,如下所示。
var s1 = {
"f01":{},
"f02":{},
"f03":{},
"f04":{},
"f05":{}
};
var s2 = indent_items(s1, ["f02", "f03", "f04"]);
s2应该以这种方式构建
{
"f01":{},
"d01":{
"f02":{},
"f03":{},
"f04":{}
},
"f05":{}
};
var s3 = indent_items(s2, ["f03", "f04"]);
s3应该以这种方式构建
{
"f01":{},
"d01":{
"f02":{},
"d02":{
"f03":{},
"f04":{}
},
},
"f05":{}
};
等深入很多层次。怎么做到这一点?
答案 0 :(得分:1)
此解决方案具有缩进的递归。
Object.keys
获取对象的所有键Array.prototype.forEach
用于迭代密钥
function indent_items(obj, array) {
function recursion(o, r) {
Object.keys(o).forEach(function (k) {
if (~array.indexOf(k)) {
r[id] = r[id] || {};
r[id][k] = o[k];
return;
}
if (typeof o[k] === 'object') {
r[k] = r[k] || {}
recursion(o[k], r[k]);
return;
}
r[k] = o[k];
});
}
var result = {},
id = 'd' + ('0' + ++count).slice(-2);
recursion(obj, result);
return result;
}
var count = 0,
s1 = { "f01": {}, "f02": {}, "f03": {}, "f04": {}, "f05": {} },
s2 = indent_items(s1, ["f02", "f03", "f04"]),
s3 = indent_items(s2, ["f03", "f04"]);
document.write('<pre>s1:' + JSON.stringify(s1, 0, 4) + '</pre>');
document.write('<pre>s2:' + JSON.stringify(s2, 0, 4) + '</pre>');
document.write('<pre>s3:' + JSON.stringify(s3, 0, 4) + '</pre>');