如何使用for循环/forEach修改API返回的响应数据结构
问题解答:将对象键值转换为带自增ID的数组对象
需求说明
调用API返回一个键为金额区间、值为统计数量的对象,需要将其转换为包含自增ID(从1开始)和对应数量的数组对象,每个元素的id按原对象键的顺序自增,count对应原对象的数值。
原始数据
const data = { "amount 100~1000": 2, "amount 1001~2000": 4, "amount 2001~3000": 1, "amount 3001~4000": 2, };
尝试的代码(存在问题)
const x = Object.values(data[0]) let id = 1; let count; let arr = []; for (let index = 0; index < x.length; index++) { id++ const obj = { id: index } arr.push(obj) } console.log(arr);// [ { id: 0 }, { id: 1 }, { id: 2 }, { id: 3 } ]
期望结果
[ { "id": 1, // amount 100~1000 "count": 2 }, { "id": 2, // amount 1001~2000 "count": 4 }, { "id": 3, // amount 2001~3000 "count": 1 }, { "id": 4, // amount 3001~4000 "count": 2 } ]
正确实现方法
方法1:使用for循环
const arr = []; // 获取对象的键值对数组,保留原顺序 const entries = Object.entries(data); for (let i = 0; i < entries.length; i++) { arr.push({ id: i + 1, // 自增ID从1开始 count: entries[i][1] // 取原对象的数值作为count }); } console.log(arr);
方法2:使用forEach遍历
const arr = []; Object.entries(data).forEach(([key, value], index) => { arr.push({ id: index + 1, count: value }); }); console.log(arr);
原代码问题说明
data[0]错误:data是对象不是数组,直接访问data[0]会得到undefined,应直接使用Object.entries(data)或Object.values(data)- 未赋值
count字段:原代码只设置了id,没有把原对象的数值赋值给count - ID逻辑错误:原代码中
id自增但未使用,反而把index(从0开始)作为id值,不符合需求的从1开始自增
内容的提问来源于stack exchange,提问作者user19304185
相关产品推荐
相关产品推荐

