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;
}
posted @ 2016-11-03 15:32  levyleo  阅读(1479)  评论(0编辑  收藏  举报