Reputation: 5345
I am having data from a json file and would like to push the data to an array. My purpose is to save the data to the database afterwards.
However, when processing the JSON I only get back:
admin:~/workspace/src (master) $ node exampleJSON.js
[]
Find below my minimum viable example:
const data = {
currency: [{},
{
Name: 'Euro',
Url: '/currencies/Euro/',
Symbol: 'EUR',
Price: '$76.3'
},
{
Name: 'Dollar',
Url: '/currencies/dollar/',
Symbol: 'DOL',
Price: '$27.61'
},
{
Name: 'Yen',
Url: '/currencies/yen/',
Symbol: 'Yen',
Price: '$638234.60'
}
]
}
const coins = []
data.currency.forEach((cur) => {
if (cur.CoinName) {
coins.push({
coinname: cur.Name,
symbol: cur.Symbol,
price: cur.Price,
createdAt: new Date(),
updatedAt: new Date(),
})
}
})
console.log(coins)
Any suggestions why there is no data in the coins
array?
I appreciate your replies!
Upvotes: 0
Views: 67
Reputation: 493
In your if condition if (cur.CoinName)
you just missed property name cur.CoinName
it should be cur.Name
Upvotes: 1
Reputation: 600
const data = {
currency: [{}, {
Name: 'Euro',
Url: '/currencies/Euro/',
Symbol: 'EUR',
Price: '$76.3'
}, {
Name: 'Dollar',
Url: '/currencies/dollar/',
Symbol: 'DOL',
Price: '$27.61'
}, {
Name: 'Yen',
Url: '/currencies/yen/',
Symbol: 'Yen',
Price: '$638234.60'
}]
}
const coins = []
data.currency.forEach((cur) => {
if (cur.Name) {
coins.push({
coinname: cur.Name,
symbol: cur.Symbol,
price: cur.Price,
createdAt: new Date(),
updatedAt: new Date(),
})
}
})
console.log(coins)
Replace cur.CoinName in if condition with cur.Name, as cur.CoinName is not any key.
Upvotes: 1
Reputation: 96
I see you have used cur.CoinName to fetch the values.There is no CoinName used anywhere in the JSON file. Instead you can use just 'cur' just like in the below code.
const coins = []
data.currency.forEach((cur) => {
if (cur.Name) {
coins.push({
coinname: cur.Name,
symbol: cur.Symbol,
price: cur.Price,
createdAt: new Date(),
updatedAt: new Date(),
})
} })
Upvotes: 2