[英]Get all Indexes of Objects in Array - from Array in Object
我正在努力處理 Object 中的一個數組,該數組存儲在一個數組中,其中包含我想要返回所有索引的對象。
Function 生成 Object 看起來像這樣:
const addArray = function(a, b) {
const object = {
name: a,
rooms: b
};
testArray.push(object);
};
我想要實現的是循環遍歷“testArray”並從 Object 返回每個索引,其中 Array Rooms 包含“Office”。
我已經嘗試過像這樣使用 function 但我似乎無法為 Object 中的數組獲得正確的語法:
function getAllIndexes(arr, val) {
var indexes = [], i = -1;
while ((i = arr.rooms.indexOf(val, i+1)) != -1){
indexes.push(i);
}
return indexes;
};
提前致謝!
編輯:數據的附加信息:
填充數據的 Object 如下所示:
const device = {
name: "TV",
rooms: ["Living Room", "Bedroom"]
};
在生成這樣的對象后,我將它們推送到一個僅包含此對象的數組中(請參閱function addArray
)
您可以使用Array.flatMap()
到 map 數組的每個值匹配val
到它的索引,並將 rest 用於空數組,這將被 flatMap 刪除:
const getAllIndexes =(arr, val) => arr.flatMap((v, i) => v === val? i: []) const arr = [1, 2, 3, 1, 2, 1, 1, 2] const result = getAllIndexes(arr, 1) console.log(result)
使用您的對象數組,您需要比較一個值,或檢查 object 是否滿足某些條件。 在這種情況下,最好用謂詞 function 替換val
:
const getAllIndexes =(arr, pred) => arr.flatMap((v, i) => pred(v)? i: []) const arr = [{ rooms: [1, 2, 3] }, { rooms: [2, 1, 1] }, { rooms: [3, 2, 2] }, { rooms: [1, 2, 1] }] const result = getAllIndexes(arr, o => o.rooms.includes(1)) console.log(result)
嘗試使用 Array.prototype.map 和 Array.prototype.filter
function getAllIndexes(arr, val) {
return arr.map(i=> {
let room = i.rooms;
return room.indexOf(val);
}).filter(a=>{
a != -1;
});
};
如果找到想要的值,您可以從設備中解構rooms
並獲取索引。
const
room = 'Office',
indices = array.flatMap(({ rooms }, i) => rooms.includes(room) ? i : []);
上面的代碼提供了我以前使用Array#flatMap
破解的解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.