简体   繁体   中英

Loop through multiple objects and get similar key values in new object

Hi I have array of objects and I am trying to loop through them and have similar key values in new object here is example of data that I have.

let newDats = [{"ID":1, "Name": "Ahmed", "Age":17, "Score":84, "Absentee":3}, 
{"ID":2, "Name": "Hassan", "Age":15, "Score":87, "Absentee":2},
{"ID":3, "Name": "Aisha", "Age":18, "Score":86, "Absentee":2}]

And so on. However, what I want is something as:

data = [{ID:[1,2,3], Names:["Ahmed", "Hassan","Aisha"], 
Ages:[17,15,18]}]

And so forth. My end goal is to perform basic descriptive statistics on the numeric parts of the data so if there is better ideas I would love to hear I am knida newbie to js.

PS

Column names (object keys ) can be more than this and unknown so I want something dynamic.

Thanks in advance.

Something like:

 let newDats = [{"ID":1, "Name": "Ahmed", "Age":17, "Score":84, "Absentee":3}, {"ID":2, "Name": "Hassan", "Age":15, "Score":87, "Absentee":2}, {"ID":3, "Name": "Aisha", "Age":18, "Score":86, "Absentee":2}]; data = {}; keys = []; for(let keyVal in newDats[0]) { keys.push(keyVal) data[keyVal] = []; } newDats.forEach(dt => { keys.forEach( kv => { data[kv].push(dt[kv]) }) }) console.log(data)

You can simply reduce() the array of objects, iterating over all Object.keys() of each element and pushing them to the property array of the accumulator. This allows for each object having different keys.

 let newDats = [{ "ID": 1, "Name": "Ahmed", "Age": 17, "Score": 84, "Absentee": 3 }, { "ID": 2, "Name": "Hassan", "Age": 15, "Score": 87, "Absentee": 2 }, { "ID": 3, "Name": "Aisha", "Age": 18, "Score": 86, "Absentee": 2 }]; const result = newDats.reduce((acc, o) => ( Object.keys(o).forEach(k => (acc[k]??= []).push(o[k])), acc), {}); console.log(result);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

Note the use of the logical nullish assignment operator (??=) which can be replaced by a logical OR short circuit for compatibility.

//acc[k] ??= []
acc[k] = acc[k] || []

You can use the function below. Just pass the array you want to sort.

 function dataSorter(dataArr) { const data = {}; for (const item in dataArr[0]) data[item] = []; for (let i = 0; i < dataArr.length; i++) { for (const item in dataArr[i]) { data[item].push(dataArr[i][item]); } } return data; } /* Example Below */ let newDats = [{ ID: 1, Name: "Ahmed", Age: 17, Score: 84, Absentee: 3 }, { ID: 2, Name: "Hassan", Age: 15, Score: 87, Absentee: 2 }, { ID: 3, Name: "Aisha", Age: 18, Score: 86, Absentee: 2 }, ]; console.log(dataSorter(newDats));
 .as-console-wrapper { max-height: 100%;important: top; 0; } // Ignore this

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