Reputation: 1638
I have two array of objects as following
const arr1 = [
{
location_ID: 1,
employee: "name",
status: "available",
},
{
location_ID: 2,
employee: "name",
status: "available",
},
];
const arr2 = [
{
assetLocation_ID: 1,
location_Name: "Yangon",
},
{
assetLocation_ID: 2,
location_Name: "Mandalay",
},
{
assetLocation_ID: 3,
location_Name: "Magway",
},
];
I am trying to find location name and insert a new field in arr1
by location_ID
so the final result would be like
const arr1 = [
{
location_ID: 1,
employee: "name",
location_Name: "Yangon",
status: "available",
},
{
location_ID: 2,
employee: "name",
location_Name: "Mandalay",
status: "available",
},
];
I've tried for
loop in arr1 and arr2.find
for arr2 but objects of arr1 is always having location of ID 1, what am I doing wrong here ? Here is my code so far
for (let i in arr1) {
arr1[i].asset_Location = arr2.find((one) => {
// one is always showing the first object of arr2
return (arr1[i].location_ID = one.assetLocation_ID);
}).location_Name;
}
Upvotes: 0
Views: 230
Reputation: 5054
You can do the following,
const result = arr1.map(item => {
const index = arr2.findIndex(asset => asset.assetLocation_ID === item.location_ID);
if(index > -1) {
return {...item, location: arr2[index].location_Name};
}
return item;
Or if you want to know what is wrong in your code,
for (let i in arr1) {
arr1[i].asset_Location = arr2.find((one) => {
// we need to return true or false from this method. You were assigning `one.assetLocation_ID` to `arr1[i].location_ID` instead of comparing them.
return arr1[i].location_ID === one.assetLocation_ID;
}).location_Name;
}
To learn more about the find method read this article.
Upvotes: 2