我已经在mongodb atlas中创建了在线集群,然后在monitch javascript编辑器中创建了mongodb Stitch应用程序,匹配时如何获取x的索引?例子:
{
"_id": 5646546,
"items":[ {"x": 12, "y": 4} , {"x": 12, "y": 4} ]
}
因此,当x = 12时索引应为0
答案 0 :(得分:0)
您可以像下面这样针脚地编写javascript函数:
const getIndex = (inputArray, match) => {
return inputArray.findIndex(element => element.x == match);
};
let obj = {
_id: 5646546,
items: [
{ x: 12, y: 4 },
{ x: 12, y: 4 }
]
};
let obj2 = {
_id: 5646547,
items: [
{ x: 121, y: 4 },
{ x: 12, y: 4 },
{ x: 122, y: 4 }
]
};
console.log(getIndex(obj.items, 12)); // prints 0
console.log(getIndex(obj2.items, 122)); // prints 2