Search and update array based on key JavaScript


We have two arrays like these −

let arr1 =
[{"LEVEL":4,"POSITION":"RGM"},{"LEVEL":5,"POSITION":"GM"},{"LEVEL":5,"POSITION":"GMH"}]
let arr2 = [{"EMAIL":"test1@stc.com","POSITION":"GM"},
{"EMAIL":"test2@stc.com","POSITION":"GMH"},
{"EMAIL":"test3@stc.com","POSITION":"RGM"},
{"EMAIL":"test3@CSR.COM.AU","POSITION":"GM"}
]

We are required to write a function that adds the property level to each object of arr2, picking it up from the object from arr1 that have the same value for property "POSITION"

Let's write the code for this function −

Example

let arr1 =
[{"LEVEL":4,"POSITION":"RGM"},{"LEVEL":5,"POSITION":"GM"},{"LEVEL":5,"POSI
TION":"GMH"}]
   let arr2 = [{"EMAIL":"test1@stc.com","POSITION":"GM"},
   {"EMAIL":"test2@stc.com","POSITION":"GMH"},
   {"EMAIL":"test3@stc.com","POSITION":"RGM"},
   {"EMAIL":"test3@CSR.COM.AU","POSITION":"GM"}
]
const formatArray = (first, second) => {
   second.forEach((el, index) => {
      const ind = first.findIndex(item => item["POSITION"] ===
      el["POSITION"]);
      if(ind !== -1){
         second[index]["LEVEL"] = first[ind]["LEVEL"];
      };
   });
};
formatArray(arr1, arr2);
console.log(arr2);

Output

The output in the console will be −

[
   { EMAIL: 'test1@stc.com', POSITION: 'GM', LEVEL: 5 },
   { EMAIL: 'test2@stc.com', POSITION: 'GMH', LEVEL: 5 },
   { EMAIL: 'test3@stc.com', POSITION: 'RGM', LEVEL: 4 },
   { EMAIL: 'test3@CSR.COM.AU', POSITION: 'GM', LEVEL: 5 }
]

Updated on: 31-Aug-2020

141 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements