简体   繁体   中英

ReactJS Object.keys().length returning number of values rather than length of array of keys

I'm trying to use Object.keys() to obtain an array of the keys from a JSON file with the following format:

[
{
    "Var1": "01-Dec-2019 00:00:00",
    "Var2": 14.55169
},
{
    "Var1": "01-Dec-2019 00:10:00",
    "Var2": 14.74149
},
{
    "Var1": "01-Dec-2019 00:20:00",
    "Var2": 13.26103
}]

Javascript:

import data from "../Data/test3data.json";

var test  = Object.keys(this.state.data).length;

When I evaluate this it returns the number of total data points (in my case 40,000) instead of 2. I can't seem to figure out why.

Oddly if I try to display the whole object I get the following error

Objects are not valid as a React child (found: object with keys {Var1, Var2})

After this line:

import data from "../Data/test3data.json";

data is equal to:

[
{
    "Var1": "01-Dec-2019 00:00:00",
    "Var2": 14.55169
},
{
    "Var1": "01-Dec-2019 00:10:00",
    "Var2": 14.74149
},
{
    "Var1": "01-Dec-2019 00:20:00",
    "Var2": 13.26103
}]

So it is an array of objects. For example, data[0] is equal:

{
    "Var1": "01-Dec-2019 00:00:00",
    "Var2": 14.55169
}

So, Object.keys(this.state.data) is [0, 1, 2] , because array indexes are the keys. And length of [0, 1, 2] is total objects count.

If you want to get Var1 , Var2 keys, you should do this:

Object.keys(this.state.data[0])

Object.keys(this.state.data[0]).length

this.state.data is an array of data points.

Object.keys(this.state.data) returns the indices of all of those data points in the array.

Object.keys(this.state.data).length returns the number of total points.

To access a specific item of this array, you need to use fe this.state.data[0] .

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