【问题标题】:Accessing a nested multi-dimensional array in AngularJS在 AngularJS 中访问嵌套的多维数组
【发布时间】:2015-09-25 14:58:36
【问题描述】:

我有两个数组。这是第一个:

$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。

我怎样才能同时获得这两个货物?

【问题讨论】:

  • 您可以在 javascript 中使用 .filter 函数。这将返回与您的表达式匹配的所有元素

标签: javascript jquery arrays angularjs


【解决方案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;

【讨论】:

  • 谢谢。这帮助我意识到我错过了什么。
【解决方案2】:

$scope.shipment 是一个没有属性 manifest 的数组,但该数组的元素是具有该属性的对象

试试

$.inArray($scope.shipment[0].manifest[0], $scope.selection)

如前所述,有更简单的方法,但我想指出问题

【讨论】:

  • 这让我回到了以前遇到的同样问题。它只是调用第一个清单。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多