我有一个对象数组,我想在获得匹配项时获取对象在数组中的索引。
我的数组如下:
let x = [
{name: "emily", info: { id: 123, gender: "female", age: 25}},
{name: "maggie", info: { id: 234, gender: "female", age: 22}},
{name: "kristy", info: { id: 564, gender: "female", age: 26}},
.....
];
目前,我使用的indexOf
最初可以正常工作,但现在无法正常工作。它返回-1
。
let find = {name: "maggie", info: { id: 234, gender: "female", age: 22}};
let index = x.indexOf(find); // should return 1.
整体应在数组中匹配,并应返回该对象的索引。我该如何实现?我应该使用some()
吗?
谢谢
答案 0 :(得分:2)
您可以使用.find
代替indexOf
,因为2个对象永远都不相等(因为它们指向内存中的不同引用),这似乎是您作为参数传递的。
let x = [
{name: "emily", info: { id: 123, gender: "female", age: 25}},
{name: "maggie", info: { id: 234, gender: "female", age: 22}},
{name: "kristy", info: { id: 564, gender: "female", age: 26}}
];
let found = x.find(function(item) {
// you can use the condition here
return item.info.id === 564;
});
console.log(found);
要查找索引,可以改用.findIndex
方法。
let x = [
{name: "emily", info: { id: 123, gender: "female", age: 25}},
{name: "maggie", info: { id: 234, gender: "female", age: 22}},
{name: "kristy", info: { id: 564, gender: "female", age: 26}}
];
let foundIndex = x.findIndex(function(item) {
// you can use the condition here
return item.info.id === 564;
});
console.log(foundIndex);
答案 1 :(得分:0)
无法通过JavaScript中的传统相等性来比较对象。而是使用ES6 findIndex
方法将每个对象的属性与所需值进行比较。这是一个示例:
let x = [
{name: "emily", info: { id: 123, gender: "female", age: 25}},
{name: "maggie", info: { id: 234, gender: "female", age: 22}},
{name: "kristy", info: { id: 564, gender: "female", age: 26}}
];
let find = {name: "maggie", info: { id: 234, gender: "female", age: 22}};
let index = x.findIndex(element => element.info.id === find.info.id); // index === 1
id
值似乎足以识别您的方案中的对象;如果您需要比较更多属性,则显然可以使用element.name === find.name
运算符添加其他相等性检查(例如&&
)。
答案 2 :(得分:0)
如果我们生活在_.lodash
的世界中,这将是可行的,因为lodash会走向deep on objects:
let data = [
{name: "emily", info: { id: 123, gender: "female", age: 25}},
{name: "maggie", info: { id: 234, age: 22, gender: "female"}},
{name: "kristy", info: { id: 564, gender: "female", age: 26}},
];
let find = {name: "maggie", info: { id: 234, gender: "female", age: 22}};
let index = _.findIndex(data, (i) => _.isEqual(i, find))
console.log(index) // 1
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
一种更野蛮的方法,显然是不 并指出,如果道具的顺序不同,则不会起作用。
let data = [
{name: "emily", info: { id: 123, gender: "female", age: 25}},
{name: "maggie", info: { id: 234, gender: "female", age: 22}},
{name: "kristy", info: { id: 564, gender: "female", age: 26}},
];
var objectJSONs = data.map((i) => JSON.stringify(i))
let myJSON = JSON.stringify({name: "maggie", info: { id: 234, gender: "female", age: 22}});
let index = objectJSONs.indexOf(myJSON)
console.log(index) // 1
答案 3 :(得分:0)
您可以使用下划线_.isEqual进行对象比较,并使用some()或任何循环机制来迭代数组。
let iFoundIndex = -1;
let bFound = x.some((data,index) => {
if(_.isEqual(data,find){
iFoundIndex = index;
return true;
}
return false;
}
//console.log(iFoundIndex);