簡體   English   中英

通過JS中的索引獲取所選項目的數組

[英]Get array of selected items by indexes in JS

我有2個數組,1個保存數據,1個保存索引,我需要使用這些索引來引用需要返回的項目。 我想遍歷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];

嘗試失敗

myData[index[myIndexes]]; // this works for 1 index, not multiple

您可以通過在索引數組上進行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) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM