k10a
k10a

Reputation: 1087

Remove key when reading json file

Try to read json file from another directory in React for options of react-select. It doesn't matter when writing json in the same file, but it doesn't work when reading from another file because it includes number of array.

1: {value: "America/New_York"name: "New York (Eastern)"}
2: {value: "America/Chicago", name: "Chicago(Central)"}
3: {value: "America/Denver", name: "Denver(Mountain)"}
4: {value: "America/Phoenix", name: "Phoenix (MST)"}

I want to remove number key. Ideal case:

{ "value": "America/Puerto_Rico", "name": "Puerto Rico (Atlantic)" },
{ "value": "America/New_York", "name": "New York (Eastern)" },
{ "value": "America/Chicago", "name": "Chicago (Central)" },
{ "value": "America/Denver", "name": "Denver (Mountain)" }

The code:

timezone.json

[
  {value: "America/New_York", name: "New York (Eastern)"}, 
  {value: "America/Chicago", name: "Chicago (Central)"},
  {value: "America/Denver", name: "Denver (Mountain)"}
]

app.js

import timezone from "./data/timezone";
console.log("timezzone", timezone);

Upvotes: 0

Views: 30

Answers (1)

Arman Safikhani
Arman Safikhani

Reputation: 945

If the json file looks like something like this:

{
   1: {value: "America/New_York", name: "New York (Eastern)"},
   2: {value: "America/Chicago", name: "Chicago(Central)"},
   3: {value: "America/Denver", name: "Denver(Mountain)"},
   4: {value: "America/Phoenix", name: "Phoenix (MST)"},
}

You can simply convert it to an array:

import timezone from "./data/timezone";
console.log(Object.values(timezone));

Object.values:

The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop. (The only difference is that a for...in loop enumerates properties in the prototype chain as well.)

Upvotes: 1

Related Questions