-
www说
您可以使用forEach和Object.entries这里的主意是首先循环遍历myObject数组中的每个元素currentObject现在,在你的结构你的价值currentObject是key在updateObject,所以我们通过检查是否存在updateObject.myObject[value]如果是他们,我们会更新,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)
-
开满天机
这样就形成了具有最新JavaScript语言功能的单行代码: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);
-
斯蒂芬大帝
我们可以在中使用Array.reduce和搜索当前元素的(ele)attribute3属性updateObject.myObject。如果存在,则使用其他中的匹配值对其进行更新,并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));