【问题标题】:Find index of object in javascript using its property name使用其属性名称在 javascript 中查找对象的索引
【发布时间】:2019-02-13 08:13:40
【问题描述】:

我想使用对象属性名称查找 javascript 对象数组的索引。我的代码是:-

const checkbox = [{'mumbai': true},{'bangalore': true},{'chennai': true},{'kolkata': true}];


我怎样才能找到钦奈的索引?我可以使用 lodash 实现吗?

【问题讨论】:

    标签: javascript arrays lodash javascript-objects


    【解决方案1】:

    您可以使用.findIndex()

    const checkbox = [
      {'mumbai': true},
      {'bangalore': true},
      {'chennai': true},
      {'kolkata': true}
    ];
    
    const finder = (arr, key) => arr.findIndex(o => key in o);
    
    console.log(finder(checkbox, 'chennai'));
    console.log(finder(checkbox, 'kolkata'));
    console.log(finder(checkbox, 'delhi'));

    【讨论】:

      【解决方案2】:
      checkbox.map((v,i) => Object.keys(v).indexOf("chennai") !== -1 ? i : -1).filter(v => v !== -1)[0]
      

      会给你“chennai”的索引,用任何其他键替换它以获得不同的索引。

      这是做什么的:

      • 将数组映射到一个数组,该数组仅指示包含具有所需键的对象的索引
      • 只过滤你想要的索引
      • 获取第一个(如果有多个条目与您的搜索匹配,您也可以使用其余的)

      这适用于所有浏览器,因为它只使用 .map() 、 Object.keys() 和 .filter()

      【讨论】:

        猜你喜欢
        • 2018-04-11
        • 2017-05-09
        • 1970-01-01
        • 1970-01-01
        • 2013-03-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-26
        相关资源
        最近更新 更多