我有两个数组。这是第一个:
$scope.selection = {
"carrots",
"celery",
"corn",
"apples",
"bananas"
};
这是第二个:
$scope.shipment = [{
"id": "0",
"name": "vegetables",
"manifest": [{"carrots", "celery", "corn"}]
}, {
"id": "1",
"name": "produce",
"manifest": [{"apples", "carrots", "bananas"}]
}];
我希望能够看到第二个数组中是否存在匹配,因为我遍历第一个数组。到目前为止,我可以使用jQuery inArray
来匹配第二个数组中的索引项:
if ($.inArray($scope.shipment.manifest[0], $scope.selection) < 0) { console.log($scope.shipment.id) };
// for "carrots"
=> "0"
但由于“胡萝卜”位于货件数组中的两个索引位置,因此上述只会返回第一个货件ID。
我怎样才能同时发货?
答案 0 :(得分:1)
首先,您的对象selection
无效。
对象是键值对,你只有字符串。它可能应该是一个数组。
其次,属性manifest
内的对象也是如此。它们也必须是数组。
修复代码时,您可以使用Array.prototype.filter
来实现您的目标:
var result = $scope.shipment.filter(function(obj) {
return obj.manifest.indexOf(item) >= 0;
});
看看我在下面创建的剪辑:
var $scope = {};
$scope.selection = [
"carrots",
"celery",
"corn",
"apples",
"bananas"
];
$scope.shipment = [{
"id": "0",
"name": "vegetables",
"manifest": ["carrots", "celery", "corn"]
}, {
"id": "1",
"name": "produce",
"manifest": ["apples", "carrots", "bananas"]
}];
var html = '';
$scope.selection.forEach(function(item, i) {
var result = $scope.shipment.filter(function(obj) {
return obj.manifest.indexOf(item) >= 0;
});
html +=
'<div>' +
'<span>Item: ' + item + '</span>' +
'</div>' +
'<div>' +
'<pre>' + JSON.stringify(result, null, 2) + '</pre>' +
'</div>';
});
document.body.innerHTML = html;
答案 1 :(得分:0)
$scope.shipment
是一个没有属性manifest
的数组,但该数组的元素是具有该属性的对象
尝试
$.inArray($scope.shipment[0].manifest[0], $scope.selection)
如上所述,有更简单的方法,但我想指出问题