繁体   English   中英

如何获取具有嵌套对象和数组的对象中每个属性的值?

[英]How to get the value of each property in an object with nested objects and arrays?

有没有一种方法可以遍历具有多个嵌套级别的对象和数组的对象并仅提取所有底层属性值?

在这个例子中,我希望它是 console.log: "Live JSON generator", 3.1, "2014-06-25T00:00:00.000Z", true 并进一步向下: "Jane Doe", "888-555-1212" , “伴侣”

 let test = { "product": "Live JSON generator", "version": 3.1, "releaseDate": "2014-06-25T00:00:00.000Z", "demo": true, "person": { "id": 12345, "name": "John Doe", "phones": { "home": "800-123-4567", "mobile": "877-123-1234" }, "email": [ "jd@example.com", "jd@example.org" ], "dateOfBirth": "1980-01-02T00:00:00.000Z", "registered": true, "emergencyContacts": [ { "name": "Jane Doe", "phone": "888-555-1212", "relationship": "spouse" }, { "name": "Justin Doe", "phone": "877-123-1212", "relationship": "parent" } ] } } for(var key in test){ console.log(test[key]); } console.log(test);

JSON.parse reviverJSON.stringify可以是检查所有值的简单方法:

 var o = {"product":"Live JSON generator","version":3.1,"releaseDate":"2014-06-25T00:00:00.000Z","demo":true,"person":{"id":12345,"name":"John Doe","phones":{"home":"800-123-4567","mobile":"877-123-1234"},"email":["jd@example.com","jd@example.org"],"dateOfBirth":"1980-01-02T00:00:00.000Z","registered":true,"emergencyContacts":[{"name":"Jane Doe","phone":"888-555-1212","relationship":"spouse"},{"name":"Justin Doe","phone":"877-123-1212","relationship":"parent"}]}} JSON.stringify(o, (k, v) => typeof v == 'object' ? v : console.log(k, ':', v))

它不起作用,因为您正在尝试读取 JSON 标记的对象,该对象与 javascript 对象不同。

尝试阅读这篇文章,它正确地解释了它。棘手的部分在最后。

而且,我的儿子就是答案所在!

祝你好运,编码愉快!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM