首页 > 随笔档案 > Node.js 对象合并

Node.js 对象合并

Publish:

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;
}

声明: 本文采用 BY-NC-SA 授权。转载请注明转自: levy