我有這兩個物件:
const tmp = {
pl: {
translation: {
states: {
foo: { name: 'bar' },
},
},
},
en: {
translation: {
states: {
foo: { name: 'bar' },
},
},
},
};
const tmp2 = {
pl: {
translation: {
states: {
foz: { name: 'baz' },
},
},
},
de: {
translation: {
states: {
foo: { name: 'bar' },
},
},
},
};
我怎樣才能連接它們?pl 部分是流暢的,它可以改變,所以它必須是動態的。
我正在考慮混合使用 Object.keys 遞回地執行此操作,但這似乎有點矯枉過正。
uj5u.com熱心網友回復:
lodashmerge將在這里解決問題:
const tmp = {
pl: { translation: { states: { foo: { name: 'bar' } } } },
en: { translation: { states: { foo: { name: 'bar' } } } },
};
const tmp2 = {
pl: { translation: { states: { foz: { name: 'baz' } } } },
de: { translation: { states: { foo: { name: 'bar' } } } },
};
console.log(_.merge(tmp, tmp2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>
uj5u.com熱心網友回復:
你去吧:
function merge(o1,o2){
const result = {}
for(const key of Object.keys(o1)) result[key] = key in o2 ? merge(o1[key],o2[key]) : o1[key];
for(const key of Object.keys(o2)) if(!(key in o1)) result[key] = o2[key];
return result;
}
uj5u.com熱心網友回復:
我建議采用更標準的方法,通用的,尤其是沒有庫的方法:
const extend = (isDeep, objects) => {
// Variables
let extended = {};
let deep = isDeep;
// Merge the object into the extended object
const merge = function (obj) {
for (let prop in obj) {
if (obj.hasOwnProperty(prop)) {
if (deep && Object.prototype.toString.call(obj[prop]) === '[object Object]') {
// If we're doing a deep merge and the property is an object
extended[prop] = extend(deep, [extended[prop], obj[prop]]);
} else {
// Otherwise, do a regular merge
extended[prop] = obj[prop];
}
}
}
};
// Loop through each object and conduct a merge
for (let argument of objects) {
merge(argument)
}
return extended;
};
你可以使用它簡單地呼叫:
extend(true, [tmp, tmp2])
第一個布爾引數用于執行深度合并或常規合并。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/384533.html
標籤:javascript 目的 数据结构
