1

Is there a simple way to convert an array of values:

dataset = [5, 10, 13];

to an array of objects, wherein each object is a key-value pair?

dataset = [ { key: 0, value: 5 },
            { key: 1, value: 10 },
            { key: 2, value: 13 } ];

This example is an abbreviated version of the dataset in the "Data Join with Keys" section of Scott Murray's Interactive Data Visualization for the Web, 2nd ed, p. 187.

I had trouble finding an answer, and therefore I am posting my own solution below.

jtr13
  • 1,225
  • 11
  • 25

2 Answers2

4

Iterate the array with Array.map(). Array.map() accepts a callback that returns a new item. The 1st param is the original item (value), the 2nd is the index (key):

const dataset = [5, 10, 13];

const result = dataset.map((value, key) => ({ key, value }));

console.log(result);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • 1
    You beat me to it and yours is more elegant. I had `dataset.map(function(d,i) {return {key: i, value: d}; } );` – jtr13 Apr 01 '18 at 21:27
4

You can use the function map

var dataset = [5, 10, 13]

var result = dataset.map((n, i) => ({ key: i, value: n }))

console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }

Another alternative, Array.from

var dataset = [5, 10, 13]

var result = Array.from(dataset, (n, i) => ({key: i, value: n}))

console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Ele
  • 33,468
  • 7
  • 37
  • 75