我有一个包含用户和点列表的json文件。我想以某种方式循环直到_id == userId,然后计算有多少对象来获取它们的位置。
到目前为止,我已经有了这个json文件,其中包含了desc顺序中的点
[
{
"_id":"55db8684ce3bf55b4b612a72",
"firstname":"Billy",
"lastname":"Bob",
"points":3109373
},
{
"_id":"55dbdffeaba8ee274d3b9f89",
"firstname":"Steve",
"lastname":"Jones",
"points":34434
},
{
"_id":"55dbdbf756b0fa064dd3e507",
"firstname":"Jim",
"lastname":"Kirk",
"points":1000
},
{
"_id":"55dbdc2756b0fa064dd3e508",
"firstname":"Casey",
"lastname":"Jones",
"points":36
},
{
"_id":"55dbdbd656b0fa064dd3e506",
"firstname":"Reg",
"lastname":"Barclay",
"points":33
},
]
我需要做的是使用他们的ID找到用户的位置。到目前为止,我的位置总是返回undefined。
$.each(obj, function(index, value) {
var returnObj = (this === "<%= user._id %>");
var position = returnObj.length;
console.log('user position is ' + position);
});
但是这总是返回未定义的11次,这就是位置应该是什么。
答案 0 :(得分:3)
如果我找到了你,那么使用for
代替each
可以使用更快,编码也不多的代码。
试试这个,
for(var i =0;i < obj.length; i++)
{
if(obj[i]['_id'] == "55dbdc2756b0fa064dd3e508"){
alert('position :' + parseInt(i + 1)); //<--position in an obj
alert('index :' + i); //<----actual index
break;
}
}
var obj=[
{
"_id":"55db8684ce3bf55b4b612a72",
"firstname":"Billy",
"lastname":"Bob",
"points":3109373
},
{
"_id":"55dbdffeaba8ee274d3b9f89",
"firstname":"Steve",
"lastname":"Jones",
"points":34434
},
{
"_id":"55dbdbf756b0fa064dd3e507",
"firstname":"Jim",
"lastname":"Kirk",
"points":1000
},
{
"_id":"55dbdc2756b0fa064dd3e508",
"firstname":"Casey",
"lastname":"Jones",
"points":36
},
{
"_id":"55dbdbd656b0fa064dd3e506",
"firstname":"Reg",
"lastname":"Barclay",
"points":33
},
]
for(var i =0;i < obj.length; i++)
{
if(obj[i]['_id'] == "55dbdc2756b0fa064dd3e508"){
alert('position :' + parseInt(i + 1));
alert('index :' + i);
break;
}
}