我有两个数组。这是第一个:
$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"
但是由于“carrots”位于发货数组中的两个索引位置,因此上面的代码只会返回第一个发货 ID。
我怎样才能收到两批 cargo ?
最佳答案
首先,您的对象选择
无效。
对象是键值对,并且里面只有字符串。它可能应该是一个数组。
其次,属性 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;
关于javascript - 访问 AngularJS 中的嵌套多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32785070/