我有兩個物件,如果兩個道具具有相同的關鍵說明,我需要合并它們并連接字串:我正在使用 lodash.js
obj1 = {
name: 'john',
address: 'cairo'
}
obj2 = {
num : '1',
address: 'egypt'
}
我需要合并的物件是這樣的:
merged = {name:"john", num: "1", address:"cairo,Egypt"}
當我嘗試使用 _.defaults(obj1,obj2) 或 _.merge(obj1,obj2) 時地址道具的問題
地址值將是 obj2 內的地址道具的值,因此我需要一種方法來合并兩個物件并連接每個物件中的兩個地址道具。
uj5u.com熱心網友回復:
嘗試這個:
function merge(obj1, obj2) {
let merged = {
...obj1,
...obj2
};
Object.keys(obj1).filter(k => obj2.hasOwnProperty(k)).forEach((k) => {
merged[k] = obj1[k] "," obj2[k]
})
return merged
}
obj1 = {
name: 'john',
address: 'cairo'
}
obj2 = {
num: '1',
address: 'egypt'
}
console.log(merge(obj1, obj2))
uj5u.com熱心網友回復:
你甚至不需要lodash. 您可以輕松地為此創建自己的功能。你可以這樣做:
new Set-在兩個輸入物件中查找所有唯一鍵for...of- 迭代上面計算的唯一鍵
function mergeObjects(obj1, obj2) {
let merged = {};
for (const property of [...new Set([...Object.keys(obj1),...Object.keys(obj2)])]) {
if(obj1[property]) merged[property] = obj1[property];
if(obj2[property]) merged[property] = merged[property] ? `${merged[property]},${obj2[property]}` : obj2[property];
}
return merged;
}
const obj1 = { name: 'john', address: 'cairo' };
const obj2 = { num : '1', address: 'egypt' };
const mergedObj = mergeObjects(obj1, obj2);
console.log(mergedObj);
uj5u.com熱心網友回復:
function mergeObjects(objArr) {
const newObj = {};
objArr.forEach((element) => {
const keys = Object.keys(element);
keys.forEach((key) => {
if (newObj[key]) newObj[key] = newObj[key] "," element[key];
else newObj[key] = element[key];
});
});
return newObj;
}
const obj1 = {name: 'john', address: 'cairo'}
const obj2 = { num : '1', address: 'egypt'}
console.log(mergeObjects([obj1, obj2]));
這樣您就可以合并任意數量的物件!
uj5u.com熱心網友回復:
您可以使用_.mergeWith()將特定鍵的值連接到陣列,然后使用_.mapValues()將陣列連接到字串:
const { mergeWith, mapValues, uniq, join } = _;
const fn = (predicate, ...objs) => mapValues(
// merge the objects
mergeWith(
{},
...objs,
// handle the keys that you want to merge in a uniqe way
(a = [], b = [], key) => predicate(key) ? a.concat(b) : undefined
),
// transform the relevant keys' values to a uniqe strings
(v, key) => predicate(key) ? uniq(v).join(', ') : v
);
const obj1 = { name: 'john', address: 'cairo' };
const obj2 = { num : '1', address: 'egypt' };
const result = fn(key => key === 'address', obj1, obj2);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG ljU96qKRCWh quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/436743.html
標籤:javascript 有角度的 打字稿 ecmascript-6 罗达什
上一篇:單擊時未呼叫單擊方法
