0

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;
    }
1
  • 2
    syntax error .. should be == here arr1[i].location_ID = one.assetLocation_ID Commented Dec 2, 2020 at 5:29

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.