通过属性获取对象的索引的JavaScript方法
给定一个对象,任务是使用JavaScript从给定属性名称和属性值的对象数组中获取对象的索引。我们将讨论一些技术。
以下是以下方法:
- 使用Array map()方法
- 使用for循环
- 使用findIndex()方法
- 使用some()方法
方法1:使用Array map()方法
该方法通过调用每个数组元素的函数返回值来创建一个新数组。该方法对数组中的每个元素调用提供的函数一次,保持顺序。
语法:
array.map(function(currentValue, index, arr), thisValue)
参数:
- function(currentValue, index, arr): 这个参数是必需的。它指定了一个函数,用于对数组中的每个元素进行操作。
- currentValue: 这个参数是必需的。它指定了当前元素的值。
- index: 这个参数是可选的。它指定了当前元素的数组索引。
- arr: 这个参数是可选的。它指定了当前元素所属的数组对象。
- thisValue: 这个参数是可选的。它指定一个值作为函数的”this”值传递。如果这个参数为空,值”undefined”将被传递。
示例:
这个示例使用 JavaScript Array map()方法 获取具有给定属性的对象的索引。
let arrayObj = [{
prop_1: 'val',
prop_2: 'val_12',
prop_3: 'val_13'
}, {
prop_1: 'val',
prop_2: 'val_22',
prop_3: 'val_23'
}];
function GFG_Fun() {
let prop = 'prop_2';
let val = 'val_22';
console.log("Index of prop = "
+ prop + " val = " + val +
" is = " +
arrayObj.map(function (e) {
return e.prop_2;
}).indexOf(val));
}
GFG_Fun();
输出
Index of prop = prop_2 val = val_22 is = 1
方法2:使用for循环
使用for循环,我们可以遍历对象数组并检查指定的prop值是否匹配。
示例1: 此示例在数组中搜索属性名和值,如果找到,返回对象的索引,否则返回-1。
let arrayObj = [{
prop_1: 'val',
prop_2: 'val_12',
prop_3: 'val_13'
}, {
prop_1: 'val',
prop_2: 'val_22',
prop_3: 'val_23'
}];
function fun_2(array, attr, value) {
for (let i = 0; i < array.length; i += 1) {
if (array[i][attr] === value) {
return i;
}
}
return -1;
}
function GFG_Fun() {
let prop = 'prop_2';
let val = 'val_22';
console.log("Index of prop = '" +
prop + "' val = '" + val + "' is = "
+ fun_2(arrayObj, prop, val));
}
GFG_Fun();
输出
Index of prop = 'prop_2' val = 'val_22' is = 1
方法3:使用 findIndex() 方法
Javascript Array.findIndex() 方法用于返回在给定数组中满足用户调用时提供的测试函数的第一个元素的索引。否则,如果找不到任何数据,则返回值为-1。 。
示例:
let arrayObj = [{
prop_1: 'val',
prop_2: 'val_12',
prop_3: 'val_13'
}, {
prop_1: 'val',
prop_2: 'val_22',
prop_3: 'val_23'
}];
const index = arrayObj.findIndex(object => {
return object.prop_3 === 'val_23';
});
console.log(index);
输出
1
方法4: 使用some()方法
Javascript的 arr.some() 方法检查数组中是否至少有一个元素满足参数方法的条件。
示例:
let arrayObj = [{
prop_1: 'val',
prop_2: 'val_12',
prop_3: 'val_13'
}, {
prop_1: 'val',
prop_2: 'val_22',
prop_3: 'val_23'
}];
let index;
arrayObj.some((object, idx) => {
if (object.prop_2 === 'val_12') {
index = idx;
return true;
}
});
console.log(index);
输出
0