我正在基于一個公共屬性合并來自兩個物件陣列的資料URL,url并且我正在使用擴展運算子將所有屬性添加到最終陣列中。
問題是,如果公共屬性value沒有相同的key名稱,它將添加“兩次”該屬性,除了更改屬性名稱或逐個添加屬性之外,還有一種方法可以使用擴展運算子排除該屬性。
const data1 = [{
url: 'google.com',
private: 'no'
},{
url: 'duckduckgo.com',
private: 'yes'
}]
const data2 = [{
URL: 'google.com',
many: true,
other: true,
properties: true,
dont: true,
want: true,
to: true,
add: true,
onebyone: true,
}]
const res = data2.map(obj => {
const otherData = data1.find(({ url }) => url === obj.URL)
return {
...obj,
...otherData
}
})
console.log(res)
.as-console-wrapper { max-height: 100% !important; top: 0; }
預期的結果將是洗掉“重復”的 URL 屬性并只url: google.com
uj5u.com熱心網友回復:
那么,為什么不直接從結果中洗掉 URL 欄位呢?
const res = data2.map(obj => {
const otherData = data1.find(({ url }) => url === obj.URL)
const result = {
...obj,
...otherData
};
delete result.URL;
return result;
})
uj5u.com熱心網友回復:
正如OP在評論中指出的那樣,
你能用我的例子并請提供和回答嗎
請在下面找到一個作業示例。我認為這是不言自明的;但是,如果有任何問題,請發布并根據需要進行解釋。
const data1 = [{
url: 'google.com',
private: 'no'
},{
url: 'duckduckgo.com',
private: 'yes'
}]
const data2 = [{
URL: 'google.com',
many: true,
other: true,
properties: true,
dont: true,
want: true,
to: true,
add: true,
onebyone: true,
}]
const res = data2.map(({ URL, ...rest }) => {
const otherData = data1.find(({ url }) => url === URL)
return {
...rest,
...otherData
}
})
console.log(res)
.as-console-wrapper { max-height: 100% !important; top: 0; }
注意:而不是obj我們解構和訪問URL和rest. 然后,在填充時,我們只需跳過URL并僅保留rest. 就是這樣。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/480854.html
標籤:javascript 数组 目的
上一篇:如何定位最后一個彈性專案
