通过JS中的索引获取所选项目的数组

时间:2018-09-07 00:01:20

标签: javascript arrays

我有2个数组,1个保存数据,1个保存索引,我需要使用它们来引用需要返回的项目。我想遍历class User def self.find_bazzes(user_id) bazs = [] self.includes(foo: [{bar: [:baz]}]).find(user_id).foos.do |foo| foo.bars.each{|bar| bazs += bar.bazs} end bazs end end 并返回索引在myData中匹配的每个项目。

数据

myIndexes

索引

myData = [
   { "name": "Do This",
     "isEditable": true
   },
   { "name": "Do That",
     "isEditable": false
   },
   { "name": "Do It Again",
     "isEditable": false
   },
   { "name": "Do It One More Time",
     "isEditable": false
   }
];

尝试失败

myIndexes = [0, 2, 3];

1 个答案:

答案 0 :(得分:3)

您可以通过在索引数组上使用map来实现。这将遍历myIndexes并通过在myData中为每个索引查找相应的元素来创建一个新数组:

var myData = [
    { "name": "Do This",
      "isEditable": true
    },
    { "name": "Do That",
      "isEditable": false
    },
    { "name": "Do It Again",
      "isEditable": false
    },
    { "name": "Do It One More Time",
      "isEditable": false
    }
 ];

var myIndexes = [0, 2, 3];
 
var selected = myIndexes.map(index => myData[index])
console.log(selected)

根据评论进行编辑:

如果您的环境不支持map,则可以随时选择老式的for循环:

var myData = [
    { "name": "Do This",
      "isEditable": true
    },
    { "name": "Do That",
      "isEditable": false
    },
    { "name": "Do It Again",
      "isEditable": false
    },
    { "name": "Do It One More Time",
      "isEditable": false
    }
 ];

var myIndexes = [0, 2, 3];

var selected = []
for (var i = 0; i < myIndexes.length; i++){
  selected.push(myData[myIndexes[i]])
}
console.log(selected)