如何从具有值的JSON对象获取索引? [英] How can I get the index from a JSON object with value?

查看:92
本文介绍了如何从具有值的JSON对象获取索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的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.

var q = MY_JSON_STRING
console.log(q.indexOf( 'allInterests' ) );

推荐答案

您将不得不使用Array.findArray.filterArray.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()将searchValue与当前元素而不是其属性匹配.您可以引用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆