如何基于 Typescript/JavaScript 中具有相同 id 的兩個不同陣列創建新陣列?
let array1 = [
{
invoiceId: 1,
name:'Ajay',
contact:'0001'
},
{
invoiceId: 2,
name:'vijay',
contact:'1234'
},
{
invoiceId: 3,
name:'Amit',
contact:'4581'
},
];
let array2 = [
{
invoiceId: 1,
age:24,
email:'[email protected]'
},
{
invoiceId: 2,
age:23,
email:'[email protected]'
},
];
在這兩個陣列中,公共欄位是基于 invoiceid 的發票 ID,必須創建新陣列,如下面的示例。
let expectedresult = [
{
name:'Ajay',
age:24
},
{
name:'vijay',
age:23
},
{
name:'Amit',
age:null
},
];
如何在 Typescript/JavaScript 中處理這個問題。有沒有基于 Lodash 的解決方案?
uj5u.com熱心網友回復:
我認為這可能是一種解決方案。
let array1 = [
{
invoiceId: 1,
name:'Ajay',
contact:'0001'
},
{
invoiceId: 2,
name:'vijay',
contact:'1234'
},
{
invoiceId: 3,
name:'Amit',
contact:'4581'
},
];
let array2 = [
{
invoiceId: 1,
age:24,
email:'[email protected]'
},
{
invoiceId: 2,
age:23,
email:'[email protected]'
},
];
console.log(array1.map(item=>({name:item.name, age: array2.filter(filteritem=>filteritem.invoiceId===item.invoiceId)[0]?.age || null})))
uj5u.com熱心網友回復:
您必須映射array1并在array2. 如果找到,則回傳姓名和年齡。
let expectedresult = array1.map(el => {
let match = array2.find(obj => obj.invoiceId === el.invoiceId)
return {
name: el.name,
age: match ? match.age : null
}
})
uj5u.com熱心網友回復:
您可以根據其鍵從array2 創建一個物件映射invoiceId,然后在遍歷array1 時輕松訪問它。
const map2 = Object.fromEntries(array2.map(item=>[item['invoiceId'], item.age]))
const expectedArray = array1.map(item=> {
return {
name: item.name,
age: map2[item.invoiceId] ? map2[item.invoiceId] : null
}
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/445714.html
標籤:javascript 反应
上一篇:array.reduce和空值
