3 回答

TA貢獻(xiàn)1775條經(jīng)驗(yàn) 獲得超8個(gè)贊
您可以使用forEach
和Object.entries
這里的主意是
首先循環(huán)遍歷
myObject
數(shù)組中的每個(gè)元素currentObject
現(xiàn)在,在你的結(jié)構(gòu)你的價(jià)值
currentObject
是key
在updateObject
,所以我們通過(guò)檢查是否存在updateObject.myObject[value]
如果是他們,我們會(huì)更新,
currentObject
否則我們將其保持不變
const currentObject = {myObject : [{'attribute1':'foo1','attribute2':'bar1','attribute3':'test1'},{'attribute1':'foo2','attribute2':'bar2','attribute3':'test2'},{'attribute1':'foo3','attribute2':'bar3','attribute3':'test3'},]}
const updateObject = {myObject : {'test1':'newtest1','test2':'newtest2','test3':'newtest3'}}
currentObject.myObject.forEach(e => {
Object.entries(e).forEach(([key,value]) => {
if(updateObject.myObject[value]){
e[key] = updateObject.myObject[value]
}
})
})
console.log(currentObject)

TA貢獻(xiàn)1786條經(jīng)驗(yàn) 獲得超13個(gè)贊
這樣就形成了具有最新JavaScript語(yǔ)言功能的單行代碼:
const currentObject = {
myObject: [
{
'attribute1': 'foo1',
'attribute2': 'bar1',
'attribute3': 'test1'
},
{
'attribute1': 'foo2',
'attribute2': 'bar2',
'attribute3': 'test2'
},
{
'attribute1': 'foo3',
'attribute2': 'bar3',
'attribute3': 'test3'
},
]
}
const updateObject = {
myObject: {
'test1': 'newtest1',
'test2': 'newtest2',
'test3': 'newtest3'
}
}
const result = { myObject: currentObject.myObject.map(o => ({ ...o, ...{ 'attribute3': updateObject.myObject[o.attribute3] } })) };
console.log(result);

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超8個(gè)贊
我們可以在中使用Array.reduce和搜索當(dāng)前元素的(ele)attribute3屬性u(píng)pdateObject.myObject。
如果存在,則使用其他中的匹配值對(duì)其進(jìn)行更新,并updateObject.myObject保留舊的:
const currentObject = {myObject : [{'attribute1':'foo1','attribute2':'bar1','attribute3':'test1'},{'attribute1':'foo2','attribute2':'bar2','attribute3':'test2'},{'attribute1':'foo3','attribute2':'bar3','attribute3':'test3'},]};
const updateObject = {myObject : {'test1':'newtest1','test2':'newtest2','test3':'newtest3'}};
function transformObject(currentObject, updateObject){
const out = currentObject.myObject.reduce((acc, ele) => {
ele.attribute3 = updateObject.myObject[ele.attribute3] ?
updateObject.myObject[ele.attribute3] :
ele.attribute3;
return acc.concat(ele);
}, []);
finalObj = {[Object.keys(currentObject)[0]] : out };
return finalObj;
}
console.log(transformObject(currentObject, updateObject));
添加回答
舉報(bào)