Merge Javascript object
This question already has an answer here:
使用Object.keys
和Array#forEach
var object1 = {
id: 1,
name: "myname",
boleanSample: true,
};
var object2 = {
unknownKeyName: "UnknownValue" //correct typo here
};
Object.keys(object2).forEach(function(key) {
object1[key] = object2[key];
});
console.log(object1);
This merge function should do it. Just remember to add the object you want to append two first.
var object1 = {
id: 1,
name: "myname",
boleanSample : true
}
var object2 = {
unknownKeyName : "UnknownValue"
}
function mergeObjects(a,b){
for(var bi in b) {
if(b.hasOwnProperty(bi)) {
if(typeof a[bi] === "undefined") {
a[bi] = b[bi];
}
}
}
}
mergeObjects(object1,object2);
console.log(object1);
Step I: loop over the properties.
Step II: try and check if object
Step III: if true, stimulate function on obj[prop] and check, else just take check.
Step IV: if there was an error obj[prop] = check;
Step V: return obj
/*functions*/
function objectConcat(o1, o2) {
for (var v in o2) {
try {
o1[v] = (o2[v].constructor == Object) ? objectConcat(o1[v], o2[v]) : o2[v];
} catch (e) {
o1[v] = o2[v];
}
}
return o1;
}
/*objects*/
var object1 = {
id: 1,
name: "myname",
boleanSample: true,
}
var object2 = {
unknownKeyName: "UnknownValue" /*mistake straighten*/
}
/*code*/
console.log(objectConcat(object2, object1));
链接地址: http://www.djcxy.com/p/27344.html
上一篇: Concat对象?
下一篇: 合并Javascript对象