Search and update array based on key JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

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 }
]
raja
Published on 31-Aug-2020 17:10:57
Advertisements