![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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