Computer >> Computer tutorials >  >> Programming >> Javascript

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":"[email protected]","POSITION":"GM"},
{"EMAIL":"[email protected]","POSITION":"GMH"},
{"EMAIL":"[email protected]","POSITION":"RGM"},
{"EMAIL":"[email protected]","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":"[email protected]","POSITION":"GM"},
   {"EMAIL":"[email protected]","POSITION":"GMH"},
   {"EMAIL":"[email protected]","POSITION":"RGM"},
   {"EMAIL":"[email protected]","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: '[email protected]', POSITION: 'GM', LEVEL: 5 },
   { EMAIL: '[email protected]', POSITION: 'GMH', LEVEL: 5 },
   { EMAIL: '[email protected]', POSITION: 'RGM', LEVEL: 4 },
   { EMAIL: '[email protected]', POSITION: 'GM', LEVEL: 5 }
]