简体   繁体   English

使用值数组创建对象数组

[英]Create array of objects using arrays of values

I have fairly lot of data in this form 我在这种形式中有相当多的数据

A B C D
-------
1 2 3 4
5 6 7 8
9 1 2 3

represented using javascript types as : 使用javascript类型表示为:

df = {A: [1,5,9], B: [2,6,1], C: [3,7,2], D:[4,8,3]}

I want to convert this into this form: 我想将其转换为这种形式:

[{A:1, B:2, C:3, D:4}, {A:5, B:6, C:7, D:8}, {A:9, B:1, C:2, D:3}]

I tried implementing it as: 我尝试将其实现为:

keyes = ["A", "B", "C", "D"]
getrow = (i) => Object.assign( ...keyes.map((k) => ({[k]: df[k][i]})))
df.A.map( (x,j) => getrow(j))

But this is slow for the size of the table I have. 但这对我所拥有的桌子的大小来说很慢。 Is there any faster way to do this? 有没有更快的方法来做到这一点?

You could use reduce and forEach loops to create array of objects. 您可以使用reduceforEach循环来创建对象数组。

 const df = { A: [1, 5, 9], B: [2, 6, 1], C: [3, 7, 2], D: [4, 8, 3] } const result = Object.keys(df).reduce((r, k) => { df[k].forEach((e, i) => { if (!r[i]) r[i] = {} r[i][k] = e; }) return r; }, []) console.log(result) 

Or maybe for better performance you can go with the for loops. 或者为了获得更好的性能,您可以使用for循环。

 const df = { A: [1, 5, 9], B: [2, 6, 1], C: [3, 7, 2], D: [4, 8, 3] } const result = []; for (let key in df) { for (let i = 0; i < df[key].length; i++) { if (!result[i]) result[i] = {} result[i][key] = df[key][i] } } console.log(result) 

You could take two for loops, and check the existence of the object at a certain index. 您可以使用两个for循环,并检查某个索引处是否存在该对象。 Then assign the value to the property. 然后将值分配给属性。

This version is faster than the use of array methods. 这个版本比使用数组方法更快。

 var data = { A: [1, 5, 9], B: [2, 6, 1], C: [3, 7, 2], D: [4, 8, 3] }, result = [], key, values, i; for ([key, values] of Object.entries(data)) { for (i = 0; i < values.length; i++) { if (!result[i]) result[i] = {}; result[i][key] = values[i]; } } console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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