英文:
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
?
英文:
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
?
答案1
得分: 1
require()
会为您进行JSON解析并返回一个对象。
您可以使用Object.values()
来获取一个仅包含此对象值的数组(忽略键):
const data = require('../../data/usershops.json');
const arr = Object.values(data)
console.log(arr);
// [ { nani: 'meow' }, { nani: 'woof' } ]
但请注意,对象中键/值的顺序是不确定的,这意味着Object.values()
返回的数组中值的顺序可能不总是您期望的顺序。<br>
除非您在数组上进行迭代并使用不依赖于它们顺序的操作,否则建议不要以这种方式使用对象。
英文:
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.<br>
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.
答案2
得分: 0
let data = {
"cat": {
"nani": "meow"
},
"dog": {
"nani": "woof"
}
};
let array = Object.entries(data).map(([key,value])=>value);
console.log(array[0].nani);
英文:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
let data = {
"cat": {
"nani": "meow"
},
"dog": {
"nani": "woof"
}
};
let array = Object.entries(data).map(([key,value])=>value);
console.log(array[0].nani);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论