I'm trying to auto-generate a JSON object for creating a dynamic interactive list message that will be sent to users on WhatsApp.
I need a JSON object in following format:
"sections": [
{
"title": "Main Title",
"rows": [
{
"title": "row 1 title",
},
{
"title": "row 2 title",
}
]
}
]
The above code will generate a list like this
But I don't want to hard code the row's title part {"title": "row 1 title",},{"title": "row 2 title", }
.
I tried using the below method where I fetch the title value from an array and merge it using spread syntax but it only returns undefined and doesn't combine all the objects.
method.js
async function genJSON() {
var arr = ['row 1', 'row 2', 'row3']
let data1, data2, d = {}
let i = 0
while (i < arr.length) {
data1 = JSON.parse(`{"title": "${arr[i]}"}`)
data2 = JSON.parse(`{"title": "${arr[i 1]}"}`)
i
d = { ...data1, ...data2 }
}
console.log(d)
catch (e) {
console.log(e)
}
}
genJSON()
Interactive List message: https://developers.facebook.com/docs/whatsapp/guides/interactive-messages/
How can I achieve the following output {"title": "row 1",},{"title": "row 2", ..} ? Any help or advice is appreciated.
CodePudding user response:
There were two issues with your code:
- You were trying to merge two dictionaries with the same keys, hence the previous key gets overwritten. Instead, you should use a JSON Array and append to it.
data2
will be undefined wheni = arr.length - 1
I've fixed both the errors in the below code snippet
function genJSON() {
var arr = ['row 1', 'row 2', 'row3']
try {
let d = []
for (const row of arr) {
d.push({
title: row
})
}
console.log(d)
} catch (e) {
console.log(e)
}
}
genJSON()