简体   繁体   English

如何遍历特定索引并检查javascript / angular中的值

[英]how to iterate over specific indexes and check values in javascript/angular

I have the following model in my angular app: 我的角度应用程序中具有以下模型:

members = [
            {
                id: 'member1',
                name: '',
                instrument1: '',
                instrument2: ''
            },...
            ]

I would like to generate a filtered array that can be accessed with an ng-repeat. 我想生成一个可以通过ng-repeat访问的过滤数组。 the filtered array would contain indexes for all instruments that have values not equal to "" or null. 过滤后的数组将包含所有值不等于“”或为null的工具的索引。 really the contents of the array are not important for the immediate term, it could just be [0,1,2....]. 实际上,数组的内容对于近期而言并不重要,它可能只是[0,1,2 ....]。

I suggest you filter the members and get the length: 我建议您过滤成员并获取长度:

function hasAnInstrument(member) {
  // return true if you want to count the member, for instance:
  return !!member.instrument1 || !!member.instrument2;
}

var counter = members.filter(hasAnInstrument).length;

EDITED ANSWER 编辑答案

var a = [
  {instrument1: true, instrument2: false},
  {instrument1: false, instrument2: false},
  {instrument1: true, instrument2: true}
];

var count = a.map(function(m) {
  return +!!m.instrument1 + +!!m.instrument2
}).reduce(function(a, b) {
  return a + b
}, 0);

console.log(count);

The map transforms each element into 0, 1 or 2 regarding of the properties converted into Booleans, and the reduce simply adds the individual counters together. 对于转换为布尔值的属性,该map将每个元素转换为0、1或2,而reduce只是将各个计数器加在一起。

Notes 笔记

  • !!something converts something into a Boolean. !!somethingsomething转换为布尔值。 +something converts something into a Number, and true is converted into 1 while false is converted into 0 . +somethingsomething转换为数字, true转换为1false转换为0 Pretty convenient. 很方便

  • This code relies on the fact that empty strings or null , when converted to a Boolean, equal false . 此代码依赖于以下事实:如果将空字符串或null转换为布尔值,则等于false This is a pretty weak thing to rely on for models, and in a production/enterprise environment, I'd suggest to make this more explicit by adding a step where the data gets sanitized. 对于模型而言,这是一件很薄弱的事情,在生产/企业环境中,我建议通过添加一个对数据进行清理的步骤来使其更加明确。

  • The code above is so concise it's almost obfuscated. 上面的代码非常简洁,几乎被混淆了。 In a production/enterprise environment, I'd suggest loosen it a little bit so it's more explicit. 在生产/企业环境中,我建议稍微松开一点,使其更加明确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM