gpt4 book ai didi

javascript - 根据key搜索并更新数组

转载 作者:行者123 更新时间:2023-11-28 12:12:10 25 4
gpt4 key购买 nike

我有两个数组,需要通过搜索第一个数组中的位置来更新第二个数组。

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

输出数组

 output  = [ {"LEVEL":5,"EMAIL":"test1@stc.com","POSITION":"GM"}, 
{"LEVEL":5,"EMAIL":"test2@stc.com",""POSITION":"GMH"},
{"LEVEL":4,"EMAIL":"test3@stc.com","POSITION":"RGM"},
{"LEVEL":5,"EMAIL":"test3@CSR.COM.AU","POSITION":"GM"}]

我尝试使用下面的代码进行过滤,但给出了空数组,因此无法进一步继续:

const output =arr1.filter((item) => {
return arr2.indexOf(item.POSITION) !== -1 && (item.POSITION)
});

最佳答案

我想你可以使用map来创建一个新数组。在那里,您可以使用 find 获取当前 POSITION 的正确 LEVEL 属性。

一种智能解决方案如下:

const positions = [{"LEVEL":4,"POSITION":"RGM"},{"LEVEL":5,"POSITION":"GM"},{"LEVEL":5,"POSITION":"GMH"}];
const emails = [{"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 result = emails.map(email => {
email['LEVEL'] = positions.find(p => p['POSITION'] === email['POSITION'])['LEVEL'];
return email;
})

console.log(result);

来自Array.prototype.map()文档:

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

来自Array.prototype.find()文档:

The find() method returns the value of the first element in the provided array that satisfies the provided testing function.

希望这会有所帮助!

关于javascript - 根据key搜索并更新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59443213/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com