Skip to content
Advertisement

Convert a const Array to JSON with specific keys [closed]

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 JavaScript:

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

Any help is appreciated.

Advertisement

Answer

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