两个对象合并成一个对象(js、jq、es6)
ES6之前就循环遍历咯,ES6浅拷贝的话可以用**Object.assign();**当然你如果项目里有jquery/underscore/lodash甚至是angular一般都有类似的extend方法咯。
像**jQuery,$.extend(obj1,obj2),**大概是这样。
jquery有一个继承方法,可以直接用
a = {'a': 1};
b = {'b': 1};
c = $.extend(a, b)或c = $.extend({}, a, b)
js如何将两个对象合并成一个对象?
nealnote
es2015 Object.assign()
var o1 = { a: 1 };
var o2 = { b: 2 };
var o3 = { c: 3 };
var obj = Object.assign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
console.log(o1); // { a: 1, b: 2, c: 3 },
注意目标对象自身也会改变。
Polyfill
if (!Object.assign) {
Object.defineProperty(
Object,
"assign",
{ enumerable: false,
configurable: true,
writable: true,
value: function(target, firstSource) {
"use strict";
if (target === undefined || target === null)
throw new TypeError("Cannot convert first argument to object");
var to = Object(target);
for (var i = 1; i < arguments.length; i++) {
var nextSource = arguments[i];
if (nextSource === undefined || nextSource === null)
continue;
var keysArray = Object.keys(Object(nextSource));
for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
var nextKey = keysArray[nextIndex];
var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
if (desc !== undefined && desc.enumerable) to[nextKey] = nextSource[nextKey];
}
}
return to;
}
}
);
}
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
prolifes
用第三方库,如:underscore、lodash等。
__=require(‘lodash’)a = {‘a’: 1};b = {‘b’: 1};c = __.extend(a, b)