如何根据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个回答

test
2024-07-05
如果你用的是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
}
]
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容