underscore.js ,遍历数组以列出特定值的所有索引

underscore.js , iterating over an array to list all index for a specific value

我有一个数组,当找到一个键的真实值时,我试图在其中迭代以获取所有索引

    sheet.headings = [
      {
        "label": "SheetId",
        "access": "R",
        "hidden": true,
        "position": "left",
        "input_type": "text"
      },
      {
        "label": "Moteur Affichage",
        "access": "W",
        "hidden": false,
        "position": "left",
        "input_type": "text",
        "value_type": "text"
      },
      {
        "label": "Navigateur",
        "access": "W",
        "hidden": true,
        "position": "left",
        "input_type": "text",
        "value_type": "text"
      }
    ]

我只能得到第一个索引,不是所有的(我应该得到[0,2]

    var column_hidden = _.findIndex(sheet.headings, function(col) {
      return col.hidden === true ;
    });

也许你可以用Array的map和filter函数来实现。类似于:

sheet.headings.map(function(e,i){
    if (e.hidden) return i;
}).filter(function(e){
    return typeof e != 'undefined';
})

首先你得到一个索引比匹配 hidden==true 的数组,然后你过滤以删除未定义的对象。