[英]Compare two arrays of objects; If second object contains the same key/value as the first return the second's, if not add key/value from the first
[英]comparing two arrays and match one key from first array's object in the second array's object if found then insert a key and value
array1 = [
{
_id: new ObjectId("639979460a52134240478a9b"),
taggedFileId: '6399798f0a52134240478abf'
},
{
_id: new ObjectId("639b576c2743a77ea2812f07"),
taggedFileId: '639988250a52134240478b07'
}
]
array2 = [
{
fileIds: new ObjectId("639979460a52134240478a9b"),
rateResult: 'none',
taggedFileId: '6399798f0a52134240478abf',
_id: new ObjectId("639c8531dcd57c7d559e6211")
},
{
fileIds: new ObjectId("639b576c2743a77ea2812f07"),
rateResult: 'none',
taggedFileId: '639988250a52134240478b07',
_id: new ObjectId("639c8531dcd57c7d559e6212")
}
]
我想用array2
的taggedFileId
檢查array1
的taggedFileId
,如果找到,則在array1
的找到索引中插入array2
的rateResult
。
結果應該如下
`
array1 = [
{
_id: new ObjectId("639979460a52134240478a9b"),
taggedFileId: '6399798f0a52134240478abf',
rateResult: 'none',
},
{
_id: new ObjectId("639b576c2743a77ea2812f07"),
taggedFileId: '639988250a52134240478b07'
rateResult: 'none',
}
]
`
您可以使用Array.find
在array2
中查找具有相同rateResult
屬性值的項目:
function ObjectId(){} array1=[{_id:new ObjectId("639979460a52134240478a9b"),taggedFileId:"6399798f0a52134240478abf"},{_id:new ObjectId("639b576c2743a77ea2812f07"),taggedFileId:"639988250a52134240478b07"}],array2=[{fileIds:new ObjectId("639979460a52134240478a9b"),rateResult:"none",taggedFileId:"6399798f0a52134240478abf",_id:new ObjectId("639c8531dcd57c7d559e6211")},{fileIds:new ObjectId("639b576c2743a77ea2812f07"),rateResult:"none",taggedFileId:"639988250a52134240478b07",_id:new ObjectId("639c8531dcd57c7d559e6212")}]; array1.forEach(({ taggedFileId }, i) => { const itm = array2.find(e => e.taggedFileId == taggedFileId) if(itm) array1[i].rateResult = itm.rateResult }) console.log(array1)
使用此代碼:
array2.forEach(item => {
const foundIndex = array1.findIndex(i => i.taggedFileId === item.taggedFileId);
if(foundIndex >= 0){
array1[foundIndex].rateResult = item.rateResult;
}
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.