I have the array below:
[
{
"Name": "Test1",
"powers": "Push",
"color": "Yellow",
"fortune": 100,
"home": "Hoth",
"transportation": "Star Destroyer"
},
{
"Name": "Test2",
"powers": "Lighning",
"color": "Yellow",
"fortune": 4004,
"home": "Tatooine",
"transportation": "Star Destroyer"
}
]
I want to separate a value below keys
You can make use of reduce
and group them based on the key:
const arr = [ { "Name": "Test1", "powers": "Push", "color": "Yellow", "fortune": 100, "home": "Hoth", "transportation": "Star Destroyer" }, { "Name": "Test2", "powers": "Lighning", "color": "Yellow", "fortune": 4004, "home": "Tatooine", "transportation": "Star Destroyer"}]; const result = arr.reduce((a,o)=>{ Object.keys(o).forEach(k=>{ (a[k]??= []).push(o[k]) }); return a; },{}); console.log(result);
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.