如何根据jsonarray里面的某一个值比较,来获取相应的集合呢?

比如说我有一个jsonarray数组

[
    {
        "title": "对",
        "option": 1,
        "score": 5
    },
    {
        "title": "错",
        "option": 2,
        "score": 0
    },
    {
        "title": "不知道",
        "option": 3,
        "score": 0
    }
]

我该如何根据jsonarray里面的option来获取到对应的集合呢?

列如:当我传的option为2时,我想要的是与之对应的集合

{
        "title": "错",
        "option": 2,
        "score": 0
},
阅读 1.9k
1 个回答

如果你用的是JAVA可以使用Google 的 Gson 库将 JSON 数据转换为 Java 对象,
教程:

https://cn.bing.com/search?q=Google+%E7%9A%84+Gson+%E5%BA%93%...

下面是js的

const jsonArray = [
  {
    "title": "对",
    "option": 1,
    "score": 5
  },
  {
    "title": "错",
    "option": 2,
    "score": 0
  },
  {
    "title": "不知道",
    "option": 3,
    "score": 0
  }
];
const result = jsonArray.find(item => item.option === 2);

result 的值:

{
  "title": "错",
  "option": 2,
  "score": 0
}

使用 Array.prototype.filter() 方法来查找多个符合条件的元素:

const jsonArray = [
  {
    "title": "对",
    "option": 1,
    "score": 5
  },
  {
    "title": "错",
    "option": 2,
    "score": 0
  },
  {
    "title": "不知道",
    "option": 3,
    "score": 0
  },
  {
    "title": "再来一个错",
    "option": 2,
    "score": 0
  }
];
const results = jsonArray.filter(item => item.option === 2);

results 的值:

[
  {
    "title": "错",
    "option": 2,
    "score": 0
  },
  {
    "title": "再来一个错",
    "option": 2,
    "score": 0
  }
]
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题