[英]Nodejs - How to find the index with two conditions, one condition being where a property exists
I have an object that looks like this:我有一个看起来像这样的对象:
{
"examples":[
{
"key":"value1"
},
{
"key":"value1",
"key2":"example"
},
{
"key":"value1"
},
{
"key":"value2"
},
{
"key":"value2",
"key2":"example"
},
{
"key":"value2"
}
]
}
I'm trying to use findIndex to find where in the object that key === 'value1'
and key2
exists (so in this instance the index would be 1).我正在尝试使用 findIndex 来查找对象中
key === 'value1'
和key2
存在的位置(因此在这种情况下,索引将为 1)。 I've tried using something like var x = examples.findIndex(({key}) => key === 'value1' && ({key2}) => key2)
but it's not working.我试过使用类似
var x = examples.findIndex(({key}) => key === 'value1' && ({key2}) => key2)
但它不起作用。 How do I go about this?我该怎么做? Any answers would be greatly appreciated!
任何答案将不胜感激! :)
:)
examples
is a property of the data object, so you need to iterate over that array. examples
是数据对象的一个属性,因此您需要遍历该数组。 examples.findIndex
won't do anything. examples.findIndex
不会做任何事情。
You can then check to see if key
has "value1" as a value, and that there is a key2
in the object.然后,您可以检查
key
是否具有“value1”作为值,并且对象中是否有key2
。
const data={examples:[{key:"value1"},{key:"value1",key2:"example"},{key:"value1"},{key:"value2"},{key:"value2",key2:"example"},{key:"value2"}]}; const result = data.examples.findIndex(obj => { return obj.key === 'value1' && obj.key2; }); console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.