Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to group object by key names that share a part of a name and convert it into array of objects?

I’m struggling to properly convert object into a grouped array of objects. Any suggestions how to get the expected results? The most important part is to group it by HIGH_PRICE and LOW_PRICE and create arrays of those grouped keys and values but it would be nice to additionally include name from what’s left from similar part of the key for example if I have HIGH_PRICE_QQQ and LOW_PRICE_QQQ the name would be QQQ.

Example of the object to sort: 

const obj = {
  HIGH_PRICE_QQQ: "10000",
  HIGH_PRICE_WWW: "2000",
  LOW_PRICE_WWW: "200",
  HIGH_PRICE_EEE: "3000",
  LOW_PRICE_EEE: "300",
}
Expected result: 

const sorted = [
  {
    name: "QQQ",
    HIGH_PRICE_QQQ: "10000",
  },
  {
    name: "WWW",
    HIGH_PRICE_WWW: "2000",
    LOW_PRICE_WWW: "200",
  },
  {
    name: "EEE",
    HIGH_PRICE_EEE: "3000",
    LOW_PRICE_EEE: "300",
  }
]

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

you can use reduce to group by the name. Finally to get the array format as you wanted use Object.values on the result.
Object.entries used to make obj iterable
split and pop used to extract the name which is last element of splitted array

const obj = {
  HIGH_PRICE_QQQ: "10000",
  HIGH_PRICE_WWW: "2000",
  LOW_PRICE_WWW: "200",
  HIGH_PRICE_EEE: "3000",
  LOW_PRICE_EEE: "300",
}

let x = Object.values(Object.entries(obj).reduce((acc,[k,v])=> {
    let name = k.split("_").pop()
  acc[name]= acc[name] || {name}
  acc[name][k] = v
  return acc
},{}))

console.log(x)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading