【问题标题】:Get all Indexes of Objects in Array - from Array in Object获取数组中对象的所有索引 - 从对象中的数组
【发布时间】:2021-02-18 20:55:43
【问题描述】:

我正在努力处理存储在数组中的对象中的数组,该数组包含我想要从中返回所有索引的对象。

生成对象的函数如下所示:

const addArray = function(a, b) {
    const object = {
        name: a,
        rooms: b
    };
    testArray.push(object);
};

我想要实现的是循环遍历“testArray”并从 Array Rooms 包含“Office”的对象返回每个索引。

我已经尝试过使用这样的函数,但我似乎无法为对象中的数组获取正确的语法:

function getAllIndexes(arr, val) {
    var indexes = [], i = -1;
    while ((i = arr.rooms.indexOf(val, i+1)) != -1){
        indexes.push(i);
    }
    return indexes;
};

提前致谢!

编辑: 数据的附加信息:

填充数据的对象如下所示:

const device = {
        name: "TV",
        rooms: ["Living Room", "Bedroom"]
    };

在生成这样的对象后,我将它们推送到一个只包含这些对象的数组中(参见function addArray

【问题讨论】:

标签: javascript arrays loops object


【解决方案1】:

您可以使用Array.flatMap() 将匹配val 的数组的每个值映射到它的索引,其余的映射到空数组,这将被 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)

使用您的对象数组,您需要比较一个值,或检查一个对象是否满足某些条件。在这种情况下,最好将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)

【讨论】:

  • 您好,感谢您的回答!如果我运行您提供的代码,它就可以正常工作,但是一旦我用我的数组替换您的数组,我就不会得到任何返回的索引。为了澄清:数组包含对象->对象包含一个名称和一个数组->我想在最后一个数组中查找索引。是否有任何其他信息可以提供帮助?谢谢!
  • @Midoxx,请将您的数据添加到问题中。
  • 输入数据示例,以及预期结果。
  • 我在问题中添加了更多信息 - 如果您需要更多信息,请告诉我!
  • 预期结果是一个扁平的索引数组?
【解决方案2】:

尝试使用 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;
    });
};

【讨论】:

    【解决方案3】:

    如果找到想要的值,您可以从设备中解构rooms 并获取索引。

    const
        room = 'Office',
        indices = array.flatMap(({ rooms }, i) => rooms.includes(room) ? i : []);
    

    上面的代码中有一个来自我的前solution 黑客Array#flatMap

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-04
      • 2014-05-14
      • 2012-02-21
      • 1970-01-01
      • 1970-01-01
      • 2017-06-16
      • 2021-03-17
      • 2017-01-07
      相关资源
      最近更新 更多