JavaScript遍历嵌套JSON对象 映射各用户skills数组长度
问题根因
for...in 遍历普通对象时,循环变量返回的永远是对象的字符串类型键名,而非键对应的属性值,这是JavaScript的固定语法规则,和JSON.parse的调用无关。你传入JSON.parse的第二个参数undefined等价于不传参,解析得到的userObj本身没有问题。
实现代码
你需要的「用户名对应用户skills数组长度」的映射,有两种可直接运行的写法:
- 写法1:修正原有
for...in逻辑,拿到键名后主动取对应的属性值
const txt = `{ "Alex": { "email": "alex@alex.com", "skills": [ "HTML", "CSS", "JavaScript" ], "age": 20, "isLoggedIn": false, "points": 30 }, "Asab": { "email": "asab@asab.com", "skills": [ "HTML", "CSS", "JavaScript", "Redux", "MongoDB", "Express", "React", "Node" ], "age": 25, "isLoggedIn": false, "points": 50 }, "Brook": { "email": "daniel@daniel.com", "skills": [ "HTML", "CSS", "JavaScript", "React", "Redux" ], "age": 30, "isLoggedIn": true, "points": 50 }, "Daniel": { "email": "daniel@alex.com", "skills": [ "HTML", "CSS", "JavaScript", "Python" ], "age": 20, "isLoggedIn": false, "points": 40 }, "John": { "email": "john@john.com", "skills": [ "HTML", "CSS", "JavaScript", "React", "Redux", "Node.js" ], "age": 20, "isLoggedIn": true, "points": 50 }, "Thomas": { "email": "thomas@thomas.com", "skills": [ "HTML", "CSS", "JavaScript", "React" ], "age": 20, "isLoggedIn": false, "points": 40 }, "Paul": { "email": "paul@paul.com", "skills": [ "HTML", "CSS", "JavaScript", "MongoDB", "Express", "React", "Node" ], "age": 20, "isLoggedIn": false, "points": 40 } }`; const userObj = JSON.parse(txt); const skillLengthMap = {}; for (const username in userObj) { // 用键名取到对应用户对象,再读取skills数组长度 skillLengthMap[username] = userObj[username].skills.length; } console.log(skillLengthMap);
- 写法2:用
Object.entries+Object.fromEntries实现,写法更简洁
const userObj = JSON.parse(txt); const skillLengthMap = Object.fromEntries( Object.entries(userObj).map(([username, userInfo]) => [username, userInfo.skills.length]) ); console.log(skillLengthMap);
结果说明
运行上述代码后得到的输出如下:
{ Alex: 3, Asab: 8, Brook: 5, Daniel: 4, John: 6, Thomas: 4, Paul: 7 }
注意你给出的预期结果存在两处笔误:一是Asab的skills实际有8项不是7项;二是原数据里对应用户名是Brook不是Brooke。
内容的提问来源于stack exchange,提问作者conradQQ
相关产品推荐
相关产品推荐

