I have two array of objects, in which if id and aid property values match then append the property code to arr1 and return the result
var arr1 = [
{ id: 1, name: "xxx", cn: "IN" },
{ id: 2, name: "yyy", cn: "MY" },
{ id: 3, name: "zzz", cn: "SG" },
]
var arr2 = [
{ aid: 1, code: "finance" },
{ aid: 2, code: "others" },
{ aid: 4, code: "finance" },
{ aid: 5, code: "product" },
]
Expected result:
var arr1 = [
{ id: 1, name: "xxx", cn: "IN", code: 'finance'},
{ id: 2, name: "yyy", cn: "MY", code: 'others'},
{ id: 3, name: "zzz", cn: "SG", code: ''},
]
I tried
var result = arr1.map(e=> ({
...e,
code: arr2.map(i=>i.code)
})
we can get like this too
var arr1 = [
{ id: 1, name: "xxx", cn: "IN" },
{ id: 2, name: "yyy", cn: "MY" },
{ id: 3, name: "zzz", cn: "SG" },
]
var arr2 = [
{ aid: 1, code: "finance" },
{ aid: 2, code: "others" },
{ aid: 4, code: "finance" },
{ aid: 5, code: "product" },
]
const fun = (ar, ar2)=>{
const getResult = ar.map((e)=> {
const Data ={
id : e.id,
name : e.name,
cn : e.cn,
code : ar2.find((e2)=> e2.aid===e.id)?.code || ""
}
return Data;
})
return getResult
}
console.log(fun(arr1, arr2))
we can usefind method too
var arr1 = [
{ id: 1, name: "xxx", cn: "IN" },
{ id: 2, name: "yyy", cn: "MY" },
{ id: 3, name: "zzz", cn: "SG" },
]
var arr2 = [
{ aid: 1, code: "finance" },
{ aid: 2, code: "others" },
{ aid: 4, code: "finance" },
{ aid: 5, code: "product" },
]
arr1.forEach(e => e.code = arr2.find(d => d.aid === e.id)?.code || '');
console.log(arr1);
You need to first find matching item in arr2 and them create the composed item.
Try like this:
var arr1 = [
{ id: 1, name: "xxx", cn: "IN" },
{ id: 2, name: "yyy", cn: "MY" },
{ id: 3, name: "zzz", cn: "SG" },
];
var arr2 = [
{ aid: 1, code: "finance" },
{ aid: 2, code: "others" },
{ aid: 4, code: "finance" },
{ aid: 5, code: "product" },
];
const result = arr1.map((item) => {
const match = arr2.find((o) => o.aid === item.id);
return { ...item, code: match ? match.code : '' };
});
console.log(result);