简体   繁体   中英

How to change an array to a JSON format with javascript

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM