如何在不使用索引的情况下按元素(在本例中为 id)过滤此 JSON?
ABC: [{
ID: home,
elementsHome: [
{
el1: x,
el2: y},
{
el3: d,
el4: s}]
},
{
ID: payments,
elementsPaymets: etc...
}];
像这样带有 ng-repeat 的 html 不起作用:ng-repeat: item in ABC.element2 |过滤器:{id:"good"}。唯一的方法是以 ABC[0] 的方式重写 ABC,但这是我想避免的。
谢谢
最佳答案
ABC.filter(function(item) {
return item.id === 'whatever you want to check'
})
Array.prototype.filter 迭代一个数组并根据您提供的函数返回一个新的过滤数组。该函数接收数组项、索引和数组作为参数。您的函数必须返回 true 或 false。如果迭代返回真,则保留,如果返回假,则删除。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
编辑
听起来您实际上是在尝试在数组中查找单个项目并访问其上的属性。因此,如果您知道自己的 ID:
var curId = 'HOME'
然后您就可以找到具有该 id 的项目:
var item = ABC.find(function(item) {
return item.id === curId
})
如果有匹配项,您可以访问所需的 key :
item && item['elements' + curId.substr(0, 1) + curId.substr(1).toLowerCase()]
关于javascript - JSON 和 Angular 。按 ID(而不是按索引)过滤数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41938244/