[英]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 = [];现在我想转换这两个对象数组,如下面的 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 .尝试使用reduce 或其他方法——但没有得到它——必须对数据数组中的列索引进行硬编码。 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 .然后使用该索引映射到
data
数组中以获取所有值——这不是一个好方法。
You can use a combination of .map() with Object.fromEntries() .您可以将.map()与Object.fromEntries()结合使用。 Since you want to map your
data
arrays to objects, you can first call .map()
on it.由于您想将
data
数组映射到对象,您可以先对其调用.map()
。 For each inner array (detonated as row
), you can build an object using Object.fromEntries()
.对于每个内部数组(引爆为
row
),您可以使用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. fromEntries()
方法采用[[key, value], ...]
对数组,您可以构建映射cols
数组,其中每个键是来自cols
的值,每个值是当前row
的关联项大批。
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 :如果您不能支持
Object.fromEntries()
,您可以使用上述使用Object.assign()和传播语法的更浏览器友好的版本:
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 */
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.