You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Swift中过滤JSON数组仅保留指定键值对?

过滤JSON数组保留指定键值对的实现方法

嘿,这个需求在日常数据处理里挺常见的,我给你分享两种主流编程语言的实现方式,你可以根据自己的技术栈来选:

JavaScript 实现

你可以用数组的map()方法遍历原数组,对每个对象只提取你需要的三个键,生成新的对象数组:

const originalData = [
  { "status" : "true", "score" : "3", "correct" : "3", "chapter" : "34", "answer" : "342432", "solutionText" : "abcd" },
  { "status" : "true", "score" : "0", "correct" : "2", "chapter" : "35", "answer" : "35854", "solutionText" : "abc" }
];

const filteredData = originalData.map(item => ({
  status: item.status,
  correct: item.correct,
  chapter: item.chapter
}));

console.log(filteredData);

运行这段代码后,就能得到你想要的过滤结果啦。

Python 实现

如果用Python处理的话,列表推导式是个简洁高效的选择:

original_data = [
    {"status": "true", "score": "3", "correct": "3", "chapter": "34", "answer": "342432", "solutionText": "abcd"},
    {"status": "true", "score": "0", "correct": "2", "chapter": "35", "answer": "35854", "solutionText": "abc"}
]

filtered_data = [
    {"status": item["status"], "correct": item["correct"], "chapter": item["chapter"]}
    for item in original_data
]

print(filtered_data)

这段代码会遍历原列表里的每个字典,只保留指定的三个键值对,输出结果完全符合你的要求。

内容的提问来源于stack exchange,提问作者AMAN SHARMA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:03:42