Carol.Kar
Carol.Kar

Reputation: 5345

Getting empty array back when processing JSON

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

Answers (3)

Rahul Patil
Rahul Patil

Reputation: 493

In your if condition if (cur.CoinName) you just missed property name cur.CoinName it should be cur.Name

Upvotes: 1

misss-popcorn
misss-popcorn

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

Ramya Makkini
Ramya Makkini

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

Related Questions