简体   繁体   中英

Get Array from JSON in reactjs

I have one problem. Anyone help me out. I am new to React so I am not able to debug it.

The problem is

When I print this.props.colors ie

console.log(this.props.colors)

I got below result.

{"colors": [["Red", true], ["Blue", false], ["Green", true], ["Black", true], ["White", false]]}

But I want it below form

0: (2) ["Red", true]
1: (2) ["Blue", false]
2: (2) ["Green", true]
3: (2) ["Black", true]
4: (2) ["White", false]

How can I get this? Anyone help me out.

Thank you.

If data - this.props.colors is:

{
  "colors": [
     ["Red", true], 
     ["Blue", false], 
     ["Green", true], 
     ["Black", true], 
     ["White", false]]
}

try this.props.colors.colors[0] or this.props.colors['colors'][0]

Also you can format colors into more comfortable array.

Use const colors = Object.values(this.props.colors) then it will return array like

[
 Array(5)
    0: ["Red", true]
    1: ["Blue", false]
    2: ["Green", true]
    3: ["Black", true]
    4: ["White", false]
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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