Node.js 对象合并
var arr = ['a', 'b', 'c', 'd'];
var json = {
a: {
f: {
g: {
h: {}
}
},
d: {},
}
};
var R = toJSON(arr);
R = copy(R,json);
console.log(R);
function toJSON(arr) {
var value = arr.shift();
var newobj = {};
newobj = newobj[value] || {};
if (arr.length > 0) {
newobj[value] = toJSON( arr);
}
return newobj;
}
function copy(newobj, obj) {
for (var attr in obj) {
newobj[attr] = newobj[attr] || {};
newobj[attr] = copy(newobj[attr], obj[attr]);
}
newobj = newobj || {};
return newobj;
}