AngularJS:通过匹配不同的属性获取数组中的对象属性?

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

我有一系列产品,显示在带有AngularJS ng-repeat的表格中。

这些产品是从Wordpress REST API调用返回的对象数组,每个对象都有一个“类别”,它以数字形式返回。

示例:{ "name": "Foo", "cat": 12 }

我不能简单地绑定到“cat”属性,因为它显示“12”而我想显示类别标签。

我可以查询所有类别的列表,并获得如下数组:

[
    { label: 'Customer Engagement Solutions', id: 2 },
    { label: 'Small and Medium Business', id: 13 },
    { label: 'Customer Information Management', id: 4 },
    { label: 'eCommerce', id: 25 },
    { label: 'Location Intelligence', id: 16 },
    { label: 'Enterprise', id: 12 }
]

我上面的产品,“Foo”应该显示“Enterprise”,即12。

我知道我可以绑定到一个函数,就像在{{ctrl.getCat(product)}}中一样,但我不确定如何将产品中的ID与类别数组中的var app = angular.module('app', []); app.controller('MainCtrl', function($scope) { const _categories = [ { label: 'Customer Engagement Solutions', id: 2 }, { label: 'Small and Medium Business', id: 13 }, { label: 'Customer Information Management', id: 4 }, { label: 'eCommerce', id: 25 }, { label: 'Location Intelligence', id: 16 }, { label: 'Enterprise', id: 12 } ]; const _products = [ { "name": "Foo", "cat": 12 }, { "name": "Bar", "cat": 16 }, { "name": "Foo Bar", "cat": 12} ] let categoryMap = {} _categories.forEach( (category)=>{ categoryMap[category.id] = category.label; }) this.products = _products.map( (product)=>{ return { "name": product.name, "category": categoryMap[product.cat] } }) });进行匹配,并返回类别标签。

这在实际的Wordpress PHP中是微不足道的,因为它们为这个任务提供了一个功能。

javascript arrays angularjs wordpress
2个回答
0
投票

最简单的方法是创建一个已经映射类别的新产品数组。使用产品和类别初始化控制器时,创建一个映射它的新阵列。

<!DOCTYPE html>
<html ng-app="app">

  <head>
    <script data-require="[email protected]" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
  </head>

  <body ng-controller="MainCtrl as ctrl">
    <div ng-repeat="product in ctrl.products">
      <span>Name: {{product.name}}</span>&nbsp;<span>Category: {{product.category}}</span>
    </div>
  </body>

</html>
Array#find()

1
投票

使用id甚至更高性能是使用ctrl.getCat = function(product){ let cat = categories.find(e => e.id === product.cat) return cat ? cat.label : 'Unknown'; } 作为属性键创建类别标签的哈希映射

使用find()

ctrl.catLabels = categories.reduce((a,c) => { a[c.id] = c.label; return a;},{})

或者作为hashmap:

{{ctrl.catLabels[product.cat]}}

然后在视图中:

qazxswpoi
© www.soinside.com 2019 - 2024. All rights reserved.