Feyza Keles
Feyza Keles

Reputation: 49

Map Json Data to new key-value pair Node.js

I want to map one json data to a new javascript object

Before:

{
    "Germany": 1,
    "France": 1
}

After

[
    {
        "name": "Germany",
        "anzahl": 1
    },
    {
        "name": "France",
        "anzahl": 1
    }
]

Here's the code:

const dataMap = Object.keys(s).map((filename, x) => {
      Object.keys(s[filename]).map((n) => ({
        anzahl: n
      }))
      return ({
        name: filename,
        anzahl: x
      });
    })

Which is giving following output:

[
    {
        "name": "Germany",
        "anzahl": 0
    },
    {
        "name": "France",
        "anzahl": 1
    }
]

Can anyone please help me out?

Upvotes: 0

Views: 1994

Answers (1)

futur
futur

Reputation: 1843

Array.prototype.map's callback's second parameter is the current index of the array, which is why x is a number beginning at 0 and incrementing. If, instead, you write it as follows:

const dataMap = Object.keys(s).map((filename) => {
    return {
        name: filename,
        anzahl: s[filename]
    }
});

This transforms each key of s into an object where name is said key, and anzahl is the result of accessing the key filename on object s.

Upvotes: 2

Related Questions