简体   繁体   中英

Use object keys to divide javascript array of objects into multiple arrays

Suppose I have an array of objects like this:

const array = [ 
{ year: 1971, temp1: 9.5, temp2: 8.0, temp3: 9.5 },
{ year: 1972, temp1: 15.0, temp2: 3.7, temp3: 94.3 },
...
{ year: 1999, temp1: 12.0, temp2: 31.0, temp3: 24.0 }
];

How might I divide this array into three arrays with the following key-value pairs (all objects having the 'year' key-value pair but different 'temp' pairs for each array):

const array1 = [ { year: 1971, temp1: 9.5}, { year: 1972, temp1: 15.0 } ... { year: 1999, temp1: 12.0 } ];

const array2 = [ { year: 1971, temp2: 8.0}, { year: 1972, temp2: 3.7 } ... { year: 1999, temp2: 31.0 } ];

const array3 = [ { year: 1971, temp3: 9.5}, { year: 1972, temp3: 94.3 } ... { year: 1999, temp3: 24.0  } ];

EDIT: I've been attempting this by trying to loop through both the Object.keys as well as the rows of the array but everything I've come up with involves looping through the entire array multiple times.

One solution could be using reduce() and while iterating over the object.keys() on each step of the reduce, you decide on which array to put a new generated object with the format {year, temp} :

 const array = [ {year: 1971, temp1: 9.5, temp2: 8.0, temp3: 9.5}, {year: 1972, temp1: 15.0, temp2: 3.7, temp3: 94.3}, {year: 1999, temp1: 12.0, temp2: 31.0, temp3: 24.0} ]; let res = array.reduce((acc, curr) => { Object.keys(curr).forEach((k, j) => { if (j > 0) { acc[j - 1] = acc[j - 1] || []; acc[j - 1].push({year: curr.year, [k]: curr[k]}); } }); return acc; }, []); console.log(res);

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