Home > Back-end >  Convert single key-value pair into multiples pairs
Convert single key-value pair into multiples pairs

Time:05-17

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.

CodePudding user response:

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);

  • Related