繁体   English   中英

获取数组中对象的所有索引 - 来自 Object 中的数组

[英]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.

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