0

I've been having trouble converting a .json file into an array object in NodeJS,

This is my JSON:

{
    "cat": {
      "nani": "meow"
    },
    "dog": {
      "nani": "woof"
    }
}

index.js:


const array = require('../../data/usershops.json');
var shop = array[0].nani
return shop;

The output in console is:

UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'nani' of undefined

It actually returns a value if I used this:

array["cat"].nani // => "meow"

How can I get the index key?

7
  • 3
    you don't have an array in your json, you have just an object there that's why trying to access by index it will not work. Commented Jan 3, 2020 at 12:43
  • @V.Sambor Thanks for replying but how do I go about making it into an array in my json? Commented Jan 3, 2020 at 12:45
  • I've updated the answer, please check how to do it. Commented Jan 3, 2020 at 12:56
  • JSON is a text representation of some data structure. Because it is text, it cannot be an array. In order to use it one needs to parse it and get back a data structure similar to the one used to create the JSON. That data structure can be an object or an array but it can even be a primitive data type (string, number, boolean etc). Use JSON.parse() to get the data structure then process it as you need. Commented Jan 3, 2020 at 13:43
  • const array = require('../../data/usershops.json'); -- require() knows how to parse JSON files and it gets you back an object. There isn't any array here. Consequently attempting to get array[0] produces an error. Use Object.values() to extract only the values from an object. It ignores the keys and returns the array you need. Commented Jan 3, 2020 at 13:46

3 Answers 3

1

require() does the JSON parsing for you and returns an object.

You can use Object.values() to get an array that contains only the values of this object (and ignore the keys):

const data = require('../../data/usershops.json');
const arr = Object.values(data)

console.log(arr);
// [ { nani: 'meow' }, { nani: 'woof' } ]

But please be aware that the order of keys/values in an object is not determined and this means the order of values in the array returned by Object.values() might not always be the one you expect.
Unless you iterate over the array and use all the values in on operation that does not depend on their order, I recommend you don't use an object this way.

Sign up to request clarification or add additional context in comments.

2 Comments

and how does this solve the index problem ? If he wants to refer to the first one as cat, object values does not assure the order... This answer is ok only if he does not care about the index
@V.Sambor Have you read the entire answer? Or only its first sentence?
0

let data = {
    "cat": {
      "nani": "meow"
    },
    "dog": {
      "nani": "woof"
    }
};

let array = Object.entries(data).map(([key,value])=>value);

console.log(array[0].nani);

6 Comments

I kind of want to use a JSON file instead of creating an array within the javascript file itself :(
There is no need to reinvent the wheel. Object.values() does exactly the same as your code.
@RinYazuki You can manipulate the object from a JSON file within the JS file. If you wish to use the JSON object as an array directly, you would have to update the JSON file itself.
@axiac , yes i know there is Object.values for values and Object.keys for keys too! The point is to show him/her how Objects can convert to array in JS.
@YazukiRin you can access JSON object or a specific key using require JSON file directly, or import if using BABEL.
|
-1

simpler:

const shop = new Array(data).flat();

1 Comment

Although this code might answer the question, I recommend that you also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.