Search code examples
javascriptarrayskey-valueecmascript-5

Convert single key-value pair into multiples pairs


A script returns me an array containing the following key-value pair :

[{"analytes":"ALBS,CRP,FR,FERHN"}]

How would you proceed in order to obtain multiple key-value pairs within an array, such as this one :

[
  {"analyte":"ALBS"},
  {"analyte":"CRP"},
  {"analyte":"FR"},
  {"analyte":"FERHN"}
]

Plus, the program i am using is still using ECMAScript 5.


Solution

  • You can use string.split() along with Array.map()

    Demo :

    const jsonObj = [{"analytes":"ALBS,CRP,FR,FERHN"}];
    
    const res = jsonObj[0].analytes.split(',').map(function(item) {
      return {"analyte": item}
    });
    
    console.log(res);