skip to Main Content

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" : "[email protected]",
  "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?

2

Answers


  1. Yea, definitely I agree it makes sense to look at a more explicit way of extracting the data you need.

    Also I think there are a few things in your example that look like they may not work but can address that as we go through the answer.

    Initially I think, if you’re looking for an approach that somewhat follows the functional approach, it makes sense to split the process of collecting the required data and compiling it into html.

    So we can create a function that is designed to take the some input in the shape of the customers field of your data and return an array of strings representing the names of each customer. I’ll put the example in typescript but you if you want to use javascript you can just ignore the types.

    The function may look like this

    const getCustomerNames = (
      customerData: (typeof data)["customers"],
    ): readonly string[] => customerData.map((data) => data.name);
    

    This is in my opinion the functional way of expressing it, where the function itself is a variable. You could also express it as a function

    
    function getCustomerNames (
      customerData: (typeof data)["customers"],
    ): readonly string[]{
        return customerData.map((data) => data.name);
    } 
    

    Here what we are doing is just mapping over each array entry of the customers data field and taking the name only.

    If you were to create a method that expects the actual data object as input you would just call it like getCustomerData(data.customers)

    And then for getting the html string from the names, you can create a function that takes as input a string array and returns a string which represents the html, for example

    const getNamesHTML = (names:readonly string[])=>names.join("</br>")
    

    This simply takes the names and joins them with a line break. Join just takes an array and joins the elements with a specified separator.

    Login or Signup to reply.
  2. I think it’s as simple as building an array and pushing the name property into it:

     function custFunction() {
       let htmlToSend = ''
    const names = [];
       for (let i = 0; i < data.customers.length; i++) {
         names.push(data.customers[i].name)
       }
       return names;
     }
    
     const data = {
       "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": "[email protected]",
       "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"
         }
       }
     }
    
    console.log(custFunction())

    But also, you seem to be using data.customer as the parameter to your function, which doesn’t seem quite right. Either pass data.customers into your function, or just use the Object (it’s not JSON; JSON is a string) itself as a global variable (as I have in my example).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search