[英]Get all Indexes of Objects in Array - from Array in Object
i´m struggling with a Array in a Object stored in a Array with Objects from which I want return all Indicies.我正在努力处理 Object 中的一个数组,该数组存储在一个数组中,其中包含我想要返回所有索引的对象。
Function to generate Object looks like this: Function 生成 Object 看起来像这样:
const addArray = function(a, b) {
const object = {
name: a,
rooms: b
};
testArray.push(object);
};
What I want to achieve is to cycle through the "testArray" and return every Index from the Object where the Array Rooms contains "Office" for example.我想要实现的是循环遍历“testArray”并从 Object 返回每个索引,其中 Array Rooms 包含“Office”。
I´ve already tried to use a function like this but I don´t seem to be able to get the right Syntax for the Array in the Object:我已经尝试过像这样使用 function 但我似乎无法为 Object 中的数组获得正确的语法:
function getAllIndexes(arr, val) {
var indexes = [], i = -1;
while ((i = arr.rooms.indexOf(val, i+1)) != -1){
indexes.push(i);
}
return indexes;
};
Thanks in advance!提前致谢!
Edit: Additional Informations to Data:编辑:数据的附加信息:
A Object with data filled would look like this:填充数据的 Object 如下所示:
const device = {
name: "TV",
rooms: ["Living Room", "Bedroom"]
};
After generating Objects like this I push them to an array witch only contains this objects (see function addArray
)在生成这样的对象后,我将它们推送到一个仅包含此对象的数组中(请参阅function addArray
)
You can use Array.flatMap()
to map each value of the array at matches val
to it's index, and the rest to empty array, which will be removed by the flatMap:您可以使用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)
Using your array of objects, you'll need to compare a value, or check if an object meets some condition.使用您的对象数组,您需要比较一个值,或检查 object 是否满足某些条件。 It's better in this case to replace val
with a predicate function:在这种情况下,最好用谓词 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)
Try using Array.prototype.map and Array.prototype.filter尝试使用 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;
});
};
You could destructure rooms
from the device and get the index, if the wanted value is found.如果找到想要的值,您可以从设备中解构rooms
并获取索引。
const
room = 'Office',
indices = array.flatMap(({ rooms }, i) => rooms.includes(room) ? i : []);
The above code features a former solution from me with hacking Array#flatMap
.上面的代码提供了我以前使用Array#flatMap
破解的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.