简体   繁体   中英

filter array of objects based on separate object values by keys using reactjs

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


  1. Name Test1 Test2
  2. powers Push Lighning
  3. color Yellow Yellow
  4. fortune 100 4004
  5. home Hoth Tatooine
  6. transportation Star Destroyer Star Destroyer

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.

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