 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 } ]Advertisements
 