-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
2020-03-08 对象合并 #3
Comments
function merge(json1, json2) {
if(!json1 || !json2) return json1 || json2
const result = {}
for (let prop in json1) {
result[prop] = json1[prop]
}
for (let prop in json2) {
// 同名属性值为 Object
if (Reflect.has(json1, prop) && isObject(json2[prop]) && isObject(json1[prop])) {
result[prop] = merge(json1[prop], json2[prop])
} else {
result[prop] = json2[prop]
}
}
return result
}
const isObject = el => {
return Object.prototype.toString.call(el) === '[object Object]'
} |
function merge(json1,json2){
const json = {};
let propName = Object.keys(json2);
for(let prop in json1 ){
json[prop] = json1[prop];
}
propName.map(function (item) {
if(json[item] === undefined){
json[item] = json2[item];
}
else{
if(typeof json[item] === "object"&& (!Array.isArray(json[item]))){
json[item] = merge(json[item],json2[item]);
}
else{
json[item] = json2[item];
}
}
})
return json;
} |
|
function merge(json1, json2) {
const json = {...json1}
for (const key in json2) {
Object.assign(json,
{[key]: Object.prototype.toString.call(json2[key] ) === '[object Object]'
? merge(json1[key], json2[key]) : json2[key]})
}
return json
}
merge(json1, json2) |
function merge(...objs) { |
function getType(value) {
try {
return Object.prototype.toString.call(value).match(/\b(\w+)\]$/)[1];
} catch(e) {
return '';
}
}
function merge(source, target) {
const result = {};
const keys = Object.keys(source);
Object.keys(target).forEach(key => !keys.includes(key) && keys.push(key));
for (const key of keys) {
const sourceType = getType(source[key]);
const targetType = getType(target[key]);
if (sourceType === targetType) {
if (sourceType === 'Object') {
result[key] = merge(source[key], target[key]);
} else {
result[key] = target[key];
}
} else if (targetType === 'Undefined') {
result[key] = source[key];
} else if (sourceType === 'Undefined') {
result[key] = target[key];
} else {
throw new Error('wrong data sturcture');
}
}
return result;
} |
function merge(target, source) { |
你这个不太行吧,对象里面但对象是要合并但。 |
const json1 = { @terrykingcha 不能用数字覆盖对象。 |
嗯你说得对!我没看清题🤪 |
不需要考虑浏览器兼容性。
The text was updated successfully, but these errors were encountered: