基于关键JavaScript搜索和更新数组

我们有两个像这样的数组-

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"}
]

我们需要编写一个将属性级别添加到arr2的每个对象的函数,并从arr1的对象中拾取该对象,该对象具有与属性“ POSITION”相同的值

让我们为该函数编写代码-

示例

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);

输出结果

控制台中的输出将为-

[
   { 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 }
]