如何使用下划线js从2个对象数组中获取不同的值

问题描述 投票:-1回答:1

如何使用下划线js从2个对象数组中获取不同的值。我有2个像这样的对象数组

var a = [{
    "asset_id": 1,
    "asset_type": 2
}, {
    "asset_id": 1,
    "asset_type": 3
}, {
    "asset_id": 3,
    "asset_type": 3
}, {
    "asset_id": 5,
    "asset_type": 2
}, {
    "asset_id": 9,
    "asset_type": 3
}, {
    "asset_id": 10,
    "asset_type": 3
}];

var b = [{
    "asset_id": 1,
    "asset_type": 2
}, {
    "asset_id": 1,
    "asset_type": 3
}, {
    "asset_id": 3,
    "asset_type": 3
}];

我的结果应该是这样的

[{
    "asset_id": 5,
    "asset_type": 2
}, {
    "asset_id": 9,
    "asset_type": 3
}, {
    "asset_id": 10,
    "asset_type": 3
}]

在underscorejs中是否有任何内置函数

javascript arrays angularjs underscore.js
1个回答
1
投票

你可以用_.reject_.findWhere来实现它。

var a = [{
    "asset_id": 1,
    "asset_type": 2
}, {
    "asset_id": 1,
    "asset_type": 3
}, {
    "asset_id": 3,
    "asset_type": 3
}, {
    "asset_id": 5,
    "asset_type": 2
}, {
    "asset_id": 9,
    "asset_type": 3
}, {
    "asset_id": 10,
    "asset_type": 3
}];

var b = [{
    "asset_id": 1,
    "asset_type": 2
}, {
    "asset_id": 1,
    "asset_type": 3
}, {
    "asset_id": 3,
    "asset_type": 3
}];

var newArr = _.reject(a, function(obj) {
  return _.findWhere(b, obj)
})

console.log(newArr)
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
© www.soinside.com 2019 - 2024. All rights reserved.