从具有值的JSON对象获取索引 [英] get index from a JSON object with value
问题描述
这是我的json字符串。
This is my json string.
[{
"name": "placeHolder",
"section": "right"
}, {
"name": "Overview",
"section": "left"
}, {
"name": "ByFunction",
"section": "left"
}, {
"name": "Time",
"section": "left"
}, {
"name": "allFit",
"section": "left"
}, {
"name": "allbMatches",
"section": "left"
}, {
"name": "allOffers",
"section": "left"
}, {
"name": "allInterests",
"section": "left"
}, {
"name": "allResponses",
"section": "left"
}, {
"name": "divChanged",
"section": "right"
}]
现在,我的值为 allInterests
,我想查找索引(这种情况;它是'7' )在上面的字符串中的这个对象。我尝试了以下代码;但它总是返回-1。有人可以帮我找出我哪里出错吗?
Now, i have the value allInterests
and i want to find out the index (this case; it is '7') of this object in the above string. I tried the following code; but it always returns -1. Can someone help me to findout where i went wrong ?
var q = MY_JSON_STRING
console.log(q.indexOf( 'allInterests' ) );
谢谢和问候,
Tismon Varghese
Thanks and regards, Tismon Varghese
推荐答案
您必须使用 Array.find
或 Array.filter
或 Array.forEach
。
因为你的值是数组,你需要元素的位置,你将拥有迭代它。
Since you value is array and you need position of element, you will have to iterate over it.
var data = [{"name":"placeHolder","section":"right"},{"name":"Overview","section":"left"},{"name":"ByFunction","section":"left"},{"name":"Time","section":"left"},{"name":"allFit","section":"left"},{"name":"allbMatches","section":"left"},{"name":"allOffers","section":"left"},{"name":"allInterests","section":"left"},{"name":"allResponses","section":"left"},{"name":"divChanged","section":"right"}];
var index = -1;
var val = "allInterests"
var filteredObj = data.find(function(item, i){
if(item.name === val){
index = i;
return i;
}
});
console.log(index, filteredObj);
var data = [{"name":"placeHolder","section":"right"},{"name":"Overview","section":"left"},{"name":"ByFunction","section":"left"},{"name":"Time","section":"left"},{"name":"allFit","section":"left"},{"name":"allbMatches","section":"left"},{"name":"allOffers","section":"left"},{"name":"allInterests","section":"left"},{"name":"allResponses","section":"left"},{"name":"divChanged","section":"right"}];
var val = "allInterests"
var index = data.findIndex(function(item, i){
return item.name === val
});
console.log(index);
默认 Array.indexOf()
将匹配se archValue到当前元素而不是它的属性。您可以参考 Array.indexOf - polyfill 在MDN上
Default Array.indexOf()
will match searchValue to current element and not its properties. You can refer Array.indexOf - polyfill on MDN
这篇关于从具有值的JSON对象获取索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!