如何在JS中将JSON响应转换为指定格式的二维矩阵?
将JSON响应转换为指定二维矩阵

需要把以下JSON响应转换成上图所示的二维矩阵,但现有代码无法实现。
原始JSON响应
{ "data": [{ "type": "articles", "id": "1", "attributes": { "title": "JSON:API paints my bikeshed!", "body": "The shortest article. Ever.", "created": "2015-05-22T14:56:29.000Z", "updated": "2015-05-22T14:56:28.000Z" }, "relationships": { "author": { "data": { "id": "42", "type": "people" } } } }], "included": [{ "type": "people", "id": "42", "attributes": { "name": "John", "age": 80, "gender": "male" } }] }
尝试过的无效代码
const response = JSON.parse({ // 此处填入上述JSON响应 }); var arr = Object.entries(response); var row = 1; var col = 4; console.log(arr[row - 1][col + 1])
解决方案
实现逻辑
- 关联文章与作者数据:从
data中提取文章信息,通过relationships里的作者ID匹配included中的作者数据。 - 提取目标字段:按照预期矩阵的结构,筛选出需要展示的字段。
- 构建二维矩阵:先创建表头数组,再组装数据行,最后组合成完整的二维矩阵。
完整代码
// 若为后端返回的字符串格式,需先用JSON.parse()解析 const response = { "data": [{ "type": "articles", "id": "1", "attributes": { "title": "JSON:API paints my bikeshed!", "body": "The shortest article. Ever.", "created": "2015-05-22T14:56:29.000Z", "updated": "2015-05-22T14:56:28.000Z" }, "relationships": { "author": { "data": { "id": "42", "type": "people" } } } }], "included": [{ "type": "people", "id": "42", "attributes": { "name": "John", "age": 80, "gender": "male" } }] }; // 提取文章核心数据 const articleInfo = response.data[0].attributes; // 匹配对应作者数据 const authorId = response.data[0].relationships.author.data.id; const authorInfo = response.included.find(item => item.id === authorId).attributes; // 构建符合要求的二维矩阵 const resultMatrix = [ ["标题", "作者", "创建时间", "年龄", "内容"], [articleInfo.title, authorInfo.name, articleInfo.created, authorInfo.age, articleInfo.body] ]; console.log(resultMatrix);
代码说明
- 直接使用响应对象(若为字符串格式,外层包裹
JSON.parse()即可)。 - 使用
find方法快速匹配作者数据,避免低效的手动遍历。 - 严格按照预期矩阵的结构组装数据,输出结果与需求完全匹配。
内容的提问来源于stack exchange,提问作者ui uk
相关产品推荐
相关产品推荐

