课程: Hands-On Introduction: JavaScript
免费学习该课程!
今天就开通帐号,24,700 门业界名师课程任您挑!
Pull only the data you need from an object - JavaScript教程
课程: Hands-On Introduction: JavaScript
Pull only the data you need from an object
- Working with data stored in objects like the JSON formatted data from a Rest API we've been working with so far. You have to keep traversing the object tree every time you want to output a specific property. For example, if I want the name of the photographer I have to traverse the tree into user and then into name. And that's what you see in our code here, "imgData.user.name." I'm traversing the object tree. This is not ideal for several reasons. First off, it's difficult to maintain and just plain clunky because you have to keep repeating that pattern. Image data, user name, image data created at image data, links, self, et cetera. Imagine a JSON object with four or five or six nested levels and you see how this will get real messy real fast. Secondly, and most importantly though, calling the properties like this makes your code less flexible because it ties your code to a specific data source and a specific object…