简体   繁体   中英

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.

Function to generate Object looks like this:

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.

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 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:

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 )

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:

 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. It's better in this case to replace val with a predicate function:

 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

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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