JS两个对象数组,如何根据元素的值,去除其中一个数组没有的元素

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

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

阅读 998
评论 2019-07-12 提问
    8 个回答
    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);
    评论 赞赏 2019-07-12