简体   繁体   中英

Using JSON File as an Array in Node.JS

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 ?

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.

 let data = { "cat": { "nani": "meow" }, "dog": { "nani": "woof" } }; let array = Object.entries(data).map(([key,value])=>value); console.log(array[0].nani);

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