【问题标题】:how to merge find difference array and array json javascript?如何合并查找差异数组和数组 json javascript?
【发布时间】:2019-03-12 09:43:06
【问题描述】:

任何人都可以帮助我合并差异两个 arrayarray json。你可以检查我下面的代码和结果,我想检查 arrarr2

之间的区别

第一个数组

let arr=[ '124', '125', '126', '127' ]

第二个数组

let arr2=[{ 
            _id: '125',
            itemId: '125',
            onHand: 10,
            inventoryValue: 70,
            avgCost: 7 
          },
          { 
            _id: '124', 
            itemId: '124', 
            onHand: 10,
            inventoryValue: 50,
            avgCost: 5 
          } 
         ]

我想要这样的结果

let arr3=['126', '127' ]

【问题讨论】:

    标签: javascript arrays json string object


    【解决方案1】:

    filter 你的arr 基于arr2 是否不包含每个值作为_id 使用some

    let arr = ['124', '125', '126', '127']
    
    let arr2 = [{
        _id: '125',
        itemId: '125',
        onHand: 10,
        inventoryValue: 70,
        avgCost: 7
      },
      {
        _id: '124',
        itemId: '124',
        onHand: 10,
        inventoryValue: 50,
        avgCost: 5
      }
    ];
    
    let arr3 = arr.filter(e => !arr2.some(({ _id }) => _id == e));
    
    console.log(arr3);

    【讨论】:

    • 哎呀 - 抱歉 @B001ᛦ,现已修复。
    • 它没有@sreypick - 我修好了。
    • 没问题@sreypick - 如果我的回答解决了您的问题,请通过单击我的回答左侧的灰色勾号将其标记为已接受。
    【解决方案2】:

    找到arr1中所有id od arr2的索引,拼接成arr1

    let arr = ['124', '125', '126', '127'];
    
    let arr2 = [{
        _id: '125',
        itemId: '125',
        onHand: 10,
        inventoryValue: 70,
        avgCost: 7
      },
      {
        _id: '124',
        itemId: '124',
        onHand: 10,
        inventoryValue: 50,
        avgCost: 5
      }
    ];
    arr2.forEach(function(element) {
          var index = arr.indexOf(element._id);
          if (index > -1) {
            arr.splice(index, 1);
          }
        });
        console.log(arr);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-31
      • 2019-08-30
      • 2016-12-06
      • 2021-04-08
      • 1970-01-01
      • 1970-01-01
      • 2020-09-19
      • 1970-01-01
      相关资源
      最近更新 更多