Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.7k views
in Technique[技术] by (71.8m points)

vue中判断两个数组里面的对象的属性值是否一样

image.png
image.png
第一个数组中的area_name和第二个数组中的chineseName一样的话 就把第二个数组中的icon赋值给第一个数组的对象中

image.png
image.png


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

第一个数组:A,第二个数组:B。

遍历 A,根据每一项的 area_name 在 B 中查找有没有 chineseName === area_name 的,找到的话就把对应的 icon 值加到当前被遍历的对象中:

A.forEach(item => {
    const matched = B.find(({ chineseName }) => chineseName === item.area_name);
    
    if (matched) {
        Object.assign(item, { icon: matched.icon });
    }
});

也可以把 B 先转成对象的形式:

const _B = Object.fromEntries(B.map(({ chineseName, ...rest }) => [chineseName, rest]));

A.forEach(item => {
    const matched = _B[item.area_name];
    
    if (matched) {
        Object.assign(item, { icon: matched.icon });
    }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...