Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
165
rated 0 times [  168] [ 3]  / answers: 1 / hits: 42151  / 7 Years ago, mon, february 20, 2017, 12:00:00

I have a JSON object that I want to iterate through.



phone: {
Samsung: {
type: S7
},
iPhone: {
type: 6S
},
Google: {
type: Pixel
}
}


I'm using Object.key to map through each of these values, which I THINK is the correct way to work with objects:



render() {
//this.props.phone contains the objects Samsung, iPhone, and Google
return (
Object.keys(this.props.phones).map((type) => {
console.log(type)
return (
<p>Type of phone: {type}</p>
)
})
)
}


However, the console.log above returns this when I was expecting an object to return:



enter



Why is it returning a value, and not an object?


More From » reactjs

 Answers
3

This is strictly speaking a answer, but it can easily be shimmed into older versions of Javascript.



You want to use either Object.values or Object.entries to loop through all the properties in an object. Where Object.keys gives you the keys, Object.values gives you the properties (well, duh) and Object.entries gives you an array [key, value] for each entry in the object.



You don't use the key in your current code, so here's the Object.values option:



    Object.values(this.props.phones).map((type) => {
console.log(type)
return (
<p>Type of phone: {type}</p>
)
})


and here's the Object.entries option, if you wanted to use both:



    Object.entries(this.props.phones).map(([make, type]) => {
console.log(make)
console.log(type)
return (
<p>Make of phone: {make}</p>
<p>Type of phone: {type}</p>
)
})


You'll see that we're using ES6 destructuring to get the two values out of the array we get from Object.entries.



The shims are linked on the MDN pages for each function.


[#58853] Saturday, February 18, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sophiak

Total Points: 242
Total Questions: 90
Total Answers: 103

Location: Liechtenstein
Member since Wed, Dec 8, 2021
2 Years ago
;