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.

0

2 Answers 2

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

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

1 Comment

You beat me to it and yours is more elegant. I had dataset.map(function(d,i) {return {key: i, value: d}; } );
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; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.