这是我的 JSON 字符串。
[{
"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。
var q = MY_JSON_STRING
console.log(q.indexOf( 'allInterests' ) );
最佳答案
您将不得不使用 Array.find
或 Array.filter
或 Array.forEach
。
由于您的值是数组并且您需要元素的位置,因此您将不得不对其进行迭代。
数组查找
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);
Array.findIndex() @ Ted Hopp的建议
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()
会将 searchValue 与当前元素匹配,而不是其属性。可以引用Array.indexOf - polyfill在 MDN 上
关于javascript - 如何从具有值的 JSON 对象中获取索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36419195/