-2

I have a json file like this below:

data.json:

[
  {
    "id": 0,
    "key": "key0",
    "value": "val0"
  },
  {
    "id": 1,
    "key": "key1",
    "value": "val1"
  },
  {
    "id": 2,
    "key": "key2",
    "value": "val2"
  },
  {
    "id": 3,
    "key": "key3",
    "value": "val3"
  }
]

Now, i want to turn this json into javascript object like this format:

JavaScript Object:

{
  key0: val0,
  key1: val1,
  key2: val2,
  key3: val3
}

I have tried to find a solution with the functions (like each, map, ...), but i couldn't find a solution. I am not just looking for a solution, but the most efficent one.

Do you have an idea?

Gaslan
  • 808
  • 1
  • 20
  • 27

1 Answers1

1

reduce is a good option here, as were reducing from an array to an object.

var json = `[
  {
    "id": 0,
    "key": "key0",
    "value": "val0"
  },
  {
    "id": 1,
    "key": "key1",
    "value": "val1"
  },
  {
    "id": 2,
    "key": "key2",
    "value": "val2"
  },
  {
    "id": 3,
    "key": "key3",
    "value": "val3"
  }
]`;

var obj = JSON.parse(json).reduce((a,v) => { a[v.key] = v.value; return a; }, {});
console.log(obj);
Keith
  • 22,005
  • 2
  • 27
  • 44