I am learning Vanilla JavaScript. I have a JSON object like below:
{
"createdBy" : "System",
"createdDate" : "2002-12-31T05:00:00.000+00:00",
"lastModifiedBy" : "System",
"lastModifiedDate" : "2023-12-31T05:00:00.000+00:00",
"id" : 2,
"softwarename" : "AcrobatReater",
"softwareprovider" : "ADOBE",
"softwareprovidercontactemail" : "admin@adobe.com",
"customers" : [ {
"name" : "CUSTOMER1",
"_links" : {
"softwares" : [ {
"href" : "http://localhost:8080/softwares/1"
}, {
"href" : "http://localhost:8080/softwares/2"
} ]
}
}, {
"name" : "CUSTOMER2",
"_links" : {
"softwares" : [ {
"href" : "http://localhost:8080/softwares/1"
}, {
"href" : "http://localhost:8080/softwares/2"
} ]
}
} ],
"_links" : {
"self" : {
"href" : "http://localhost:8080/softwares/2"
},
"appSoftware" : {
"href" : "http://localhost:8080/softwares/2"
}
}
}
To get the names of customers I am doing it like this:
function custFunction(data.customers) {
let htmlToSend = ''
for (let i = 0; i < data.customers.length; i++) {
const [key, val] = Object.entries(data.customers[i]);
htmlToSend += `${key.toString().split(',')[1]}</br>`;
}
return htmlToSend;
}
This is getting the job done but it seems like a dirty solution. I am worried what if the more fields are introduced at the entity level, it may break. Is there a better way to get just the name’s values (CUSTOMER1 and CUSTOMER2 in this case). Is there any functional style of coding to achieve it where we can just target the names and their values only?
>Solution :
I think you are doing too much in your custom code, this functionality is already covered by Javascript built-in modules. And, as you imagined, in a functional style.
data.customers.map(c => c.name).join("</br>")
That is it. It would return "CUSTOMER1</br>CUSTOMER2". If you actually want the output to be "CUSTOMER1</br>CUSTOMER2</br>", you could do this, instead:
data.customers.map(c => c.name + "</br>").join("")
Doing anything more than that is just overdoing it.