Home > Mobile >  How to change an array to a JSON format with javascript
How to change an array to a JSON format with javascript

Time:09-26

I have an array which is in the below format node=['ADSss|623', 'sss|635'] I want this to be in a json format as below

[
    {
        "623": "ADSss"
    },
    {"635": "sss"

    }

]

Is there a simple way to achieve this? it is possible with map function, but i felt it is adding up too many lines of code

CodePudding user response:

Assuming that you array only contain string of format ${value}|${key}, you can map those to an object:

const result = node.map((arrayEl) => {
  // Split you array string into value and keys
  const [value, key] = arrayEl.split('|');
  // return an object key: value
  return {[key]: value}
});
console.log(result);

CodePudding user response:

You can use string.split and Array.map functions to achieve what you want.

const source = ['ADSss|623', 'sss|635']

const target = source.map(r => {
  const [value, key] = r.split('|'); 
  return {
    [key]: value
  };
})
console.log(target)

CodePudding user response:

In one line :

const node=['ADSss|623', 'sss|635'];
const json = node.reduce((p, n) => ({ ...p, [n.split('|')[1]]: n.split('|')[0] }), {});
const jsonArray = node.map(n => ({ [n.split('|')[1]]: n.split('|')[0] }));

console.log(json);
console.log(jsonArray);

  • Related