Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert a const Array to JSON with specific keys

I have an array like this:

const faces= [
    [[128516], "grinning face with smiling eyes", "20201001"],
    [[128512], "grinning face", "20201001"],
    [[128578], "slightly smiling face", "20201001"],
    [[128579], "upside-down face", "20201001"],
    [[128521], "winking face", "20201001"]
]

And I want to convert it to a formatted JSON like this using Java or JavaScript, different but both are fine:

[
  {
    "id": 128516,
    "name": "grinning face with smiling eyes",
    "date": "20201001"
  },
  {
    "id": 128512,
    "name": "grinning face",
    "date": "20201001"
  }
]

Any help is appreciated.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

const faces = [
  [
    [128516], "grinning face with smiling eyes", "20201001"
  ],
  [
    [128512], "grinning face", "20201001"
  ],
  [
    [128578], "slightly smiling face", "20201001"
  ],
  [
    [128579], "upside-down face", "20201001"
  ],
  [
    [128521], "winking face", "20201001"
  ]
]

let result = []
faces.forEach(item => {
  let a = {
    id: item[0][0],
    name: item[1],
    date: item[2]
  }
  result.push(a)
})

console.log(JSON.stringify(result))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading