1
const array1 = [
   {currency: 'CNY', value: 1 },
   {currency: 'USD', value: 2 }
]

const array2 = [
   {currency: 'CNY', value: 332 },
   {currency: 'USD', value: 424 },
   {currency: 'HK', value: 123 }
]

数组array1array2,现在需要根据array1子元素的currency字段,删除array2中多余的子元素,
即得到

const array2 = [
   {currency: 'CNY', value: 332 },
   {currency: 'USD', value: 424 }
]

怎么写啊,,想了好久都没实现~~~!!!!

Demo_Hu 488
7月12日提问

查看全部 8 个回答

1
var array1 = [
   {currency: 'CNY', value: 1 },
   {currency: 'USD', value: 2 }
]
var array2 = [
   {currency: 'CNY', value: 332 },
   {currency: 'USD', value: 424 },
   {currency: 'HK', value: 123 }
]

function arrFormat(arr1,arr2){
    let newarr=[];
    for (let i = 0; i < arr1.length; i++) {
        for (let j = 0; j < arr2.length; j++) {
           if(arr2[j].currency==arr1[i].currency){
                newarr.push(arr1[i]);
        }
        }
        
    }
    return newarr;
}
array2 = arrFormat(array1,array2);
console.log(array2);

推荐答案

5

已采纳
let result = array2.filter(item => array1.some(value => value.currency == item.currency))

推广链接