简体   繁体   中英

Convert array of values to array of objects (key-value) pairs in JavaScript

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM