underscoreJS-形成一个新数组,其中包含array1中的项但不包含在array2中

时间:2016-05-02 10:36:19

标签: underscore.js

假设我有array1和array2,需要找到一个方法,通过该方法我可以在array1中找到但不在array2中的项目,

array1":[{"name":"tom","lastname":"jacob","emailId":"tomjacob@gmail.com","$$key":"object:4"},{"name":"will","lastname":"rogers","emailId":"willrogers@gmail.com","$$key":"object:24"},{"name":"matt","lastname":"jacob","emailId":"mattjacob@gmail.com","$$key":"object:84"}]
array2":[{"name":"tom","lastname":"jacob","emailId":"tomjacob@gmail.com","$$key":"object:4"},{"name":"matt","lastname":"jacob","emailId":"mattjacob@gmail.com","$$key":"object:84"}]
**i need to get a new array** 
**result:**[{"name":"will","lastname":"rogers","emailId":"willrogers@gmail.com","$$key":"object:24"}]

1 个答案:

答案 0 :(得分:0)

您可以使用rejectsome

var result = _.reject(data.array1, item => _.some(data.array2, { $$key : item.$$key}));

或没有箭头功能:

var result = _.reject(data.array1, function(item) {
    return _.some(data.array2, { $$key : item.$$key}); 
});

var data = {
	"array1":[
		{"name":"tom","lastname":"jacob","emailId":"tomjacob@gmail.com","$$key":"object:4"},
		{"name":"will","lastname":"rogers","emailId":"willrogers@gmail.com","$$key":"object:24"},
		{"name":"matt","lastname":"jacob","emailId":"mattjacob@gmail.com","$$key":"object:84"}],

	"array2":[
		{"name":"tom","lastname":"jacob","emailId":"tomjacob@gmail.com","$$key":"object:4"},
		{"name":"matt","lastname":"jacob","emailId":"mattjacob@gmail.com","$$key":"object:84"}]
}

var result = _.reject(data.array1, item => _.some(data.array2, { $$key : item.$$key}));

document.getElementById('result').textContent = JSON.stringify(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore.js"></script>

<p>
  <pre id="result"></pre>
</p>