-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?

1
  • JSON.parse() and Object.assign Commented Oct 30, 2017 at 21:38

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.