简体   繁体   中英

Dataset to an array of objects in Javascript/Typescript

I have a input object of two array

payload 

columns:["col1" , "col2","col3"],
data: ["col1value1","col2value1" , "col1value3"] ,
      ["col1value2","col2value2" , "col1value2"]
 

Now I want to convert this two array of objects like below output = [];

[
  { col1: 'col1value1', col2: 'col2value1', col3: col1value3},
  { col1: 'col1value2', col2: 'col2value2', col3: col1value2}
]

trying to use reduce or other methods -- but not getting it - have to hard code index of column in data array . is there any better and fast way? in which it will done without hard coding the column names.

currently doing like

const indexofCol1= this.payload.columns.indexOf["col1"]

then using that index to map in data array to get all the values -- which is not a good way .

You can use a combination of .map() with Object.fromEntries() . Since you want to map your data arrays to objects, you can first call .map() on it. For each inner array (detonated as row ), you can build an object using Object.fromEntries() . The fromEntries() method takes an array of [[key, value], ...] pairs, which you can construct mapping your cols array, where each key is a value from cols and each value is the associated item in your current row array.

See example below:

 const cols = ["col1" , "col2","col3"]; const data = [["col1value1","col2value1" , "col1value3"], ["col1value2","col2value2" , "col1value2"]]; const res = data.map(row => Object.fromEntries( cols.map((key, i) => [key, row[i]]) )); console.log(res);
 .as-console-wrapper { max-height: 100% !important;} /* ignore */

If you cannot support Object.fromEntries() , you can use a more browser-friendly version of the above which uses Object.assign() and the spread syntax :

 const cols = ["col1" , "col2","col3"]; const data = [["col1value1","col2value1" , "col1value3"], ["col1value2","col2value2" , "col1value2"]]; const res = data.map(row => Object.assign({}, ...cols.map((key, i) => ({[key]: row[i]})) )); console.log(res);
 .as-console-wrapper { max-height: 100% !important;} /* ignore */

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