Skip to content

How to create JSON Object in JavaScript?

I have JSON like this :

{
   "success":true,
   "data":[
      {
         "id": 1,
         "markname":"nama_penduduk",
         "markvalue":"Vin Diesel"
      },
      {
         "id": 2,
         "markname":"umur_penduduk",
         "markvalue":"20 Tahun"
      },
      {
         "id": 3,
         "markname":"keperluan_membuat_surat",
         "markvalue":"Untuk uji coba surat"
      }
   ]
}

I’m trying to create a JSON like this :

const newJSON = {
    nama_penduduk: 'Vin Diesel',
    umur_penduduk: '20 Tahun',
    keperluan_membuat_surat: 'Untuk uji coba surat'
};

Code :

dataResult.map((value) => {
  const markName = value.markname;
  const markValue = value.markvalue;

  res.status(200).json({
      markName: markValue
  });
});

Suppose I don’t know how many data I have, how do I create this object in JavaScript?

Answer

You can use Array.reduce()

const dataResult = [{
    "id": 1,
    "markname": "nama_penduduk",
    "markvalue": "Vin Diesel"
  },
  {
    "id": 2,
    "markname": "umur_penduduk",
    "markvalue": "20 Tahun"
  },
  {
    "id": 3,
    "markname": "keperluan_membuat_surat",
    "markvalue": "Untuk uji coba surat"
  }
]

const newJSON = dataResult.reduce((acc, cur) => {
  acc[cur.markname] = cur.markvalue;
  return acc;
}, {});

console.log(newJSON);