简体   繁体   English

派生索引数组

[英]Deriving an array of indexes

This is a continuation of exploration traversing data structures in JavaScript. 这是JavaScript中遍历数据结构的探索的延续。 See here and here . 看到这里这里

Given this Javascript object: 给定此Javascript对象:

var parsed =       {
  "terms": [
    {
      "span": [
        12,
        13
      ],
      "value": "2",
      "label": "number"
    },
    {
      "span": [
        13,
        14
      ],
      "value": "x",
      "label": "multiply"
    },
    {
      "span": [
        14,
        16
      ],
      "value": "14",
      "label": "number"
    },
  ],
  "span": [
    12,
    21
  ],
  "weight": 0.85,
  "value": "2x14 test"
};

How would I derive an array of the indexes of the terms where the label: number? 我将如何得出标签:数字的术语索引数组?

In a previous question, noted above, I was able to solve the notion of deriving the index for a certain label, when it was known that there was only one instance of such. 在上面提到的上一个问题中,当已知只有一个实例时,我能够解决为特定标签派生索引的概念。

parsed.terms.map(function(d){ return d['label']; }).indexOf('number');

Now I am faced with the notion of multiple instances, as in the object above. 现在,我面临着多个实例的概念,就像上面的对象一样。 The above code snip will only derive the index of the first. 上面的代码片段将仅得出第一个的索引。

I could build an array by looping through the terms and see if each has a number label, however the ideal solution would perhaps expand or modify the code snip above and perhaps not use a loop. 我可以通过遍历这些术语来构建数组,看看每个术语是否都有数字标签,但是理想的解决方案可能是扩展或修改上面的代码片段,也许不使用循环。

When you need to map and filter simultaneously use reduce : 当您需要同时映射和过滤时,请使用reduce

var indexes = parsed.terms.reduce(function(indexCollection, item, index) {
    if(item.label === 'number') {
        indexCollection.push(index);
    }

    return indexCollection;
}, []); 

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

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