Home > Net >  Javascript: From JSON array of strings in the form of key:value to array of objects
Javascript: From JSON array of strings in the form of key:value to array of objects

Time:08-05

say that I receive this JSON array from an API call.

[
  "{'apple': 'enabled'}",
  "{'banana': 'disabled'}"
] 

How do I transform it into this:

[
  {
    label: 'apple',
    value: 'enabled'
  },
  {
    label: 'banana',
    value: 'disabled'
  }
]

The number of fields and the values are of course variable.

With JSON5.parse() I can transform it into this:

[
  {
    apple: 'enabled',
  },
  {
    banana: 'disabled'
  }
]

But this is still not what I need.

How can I achieve the transformation I need, without hacky workarounds that might change the values inside?

Thank you

CodePudding user response:

const apiArray = [
  "{'apple': 'enabled'}",
  "{'banana': 'disabled'}"
];

const returnArray = [];

for (const element of apiArray) {
  const parsedObj = JSON.parse(element);
  const label = Object.keys(element)[0];
  const value = parsedObj[label];

  returnArray.push({"label": label, "value": value});
}

This inspects every element of the initial array on its own and extracts the label and the value. These then get pushed into the returnArray in the correct format.

CodePudding user response:

I managed to make it work with this: (Thanks @Alexander)

data.map(el=>{
  const parsed = JSON5.parse(el)
  return{
    label: Object.keys(parsed)[0],
    value: Object.values(parsed)[0] 
  }
})

However, it is not very clean.

CodePudding user response:

you can try this

var newArr = [];
apiArray.forEach((element) => {
  let obj = JSON.parse(element.replaceAll("'", '"'));
  newArr.push({ label: Object.keys(obj)[0], value: Object.values(obj)[0] });
});

console.log(JSON.stringify(newArr));

CodePudding user response:

you can try something like this :

myArray.map((data) => {
  const parsedData = JSON.parse(data);
  return {
    label: Object.keys(parsedData).join(),
    value: Object.values(parsedData).join(),
  };
});

Output :

[{
    "label": "apple",
    "value": "enabled"
},
{
    "label": "banana",
    "value": "disabled"
}]
  • Related