I have JSON like this :
JavaScript
x
21
21
1
{
2
"success":true,
3
"data":[
4
{
5
"id": 1,
6
"markname":"nama_penduduk",
7
"markvalue":"Vin Diesel"
8
},
9
{
10
"id": 2,
11
"markname":"umur_penduduk",
12
"markvalue":"20 Tahun"
13
},
14
{
15
"id": 3,
16
"markname":"keperluan_membuat_surat",
17
"markvalue":"Untuk uji coba surat"
18
}
19
]
20
}
21
I’m trying to create a JSON like this :
JavaScript
1
6
1
const newJSON = {
2
nama_penduduk: 'Vin Diesel',
3
umur_penduduk: '20 Tahun',
4
keperluan_membuat_surat: 'Untuk uji coba surat'
5
};
6
Code :
JavaScript
1
9
1
dataResult.map((value) => {
2
const markName = value.markname;
3
const markValue = value.markvalue;
4
5
res.status(200).json({
6
markName: markValue
7
});
8
});
9
Suppose I don’t know how many data I have, how do I create this object in JavaScript?
Advertisement
Answer
You can use Array.reduce()
JavaScript
1
23
23
1
const dataResult = [{
2
"id": 1,
3
"markname": "nama_penduduk",
4
"markvalue": "Vin Diesel"
5
},
6
{
7
"id": 2,
8
"markname": "umur_penduduk",
9
"markvalue": "20 Tahun"
10
},
11
{
12
"id": 3,
13
"markname": "keperluan_membuat_surat",
14
"markvalue": "Untuk uji coba surat"
15
}
16
]
17
18
const newJSON = dataResult.reduce((acc, cur) => {
19
acc[cur.markname] = cur.markvalue;
20
return acc;
21
}, {});
22
23
console.log(newJSON);