A guide on iterating through a JSON object in Vue and Javascript to retrieve keys and values, checking if they are either distinct or null

Looking for a way to iterate through a JSON object that may or may not have properties fields, which can be null or contain various configurations. I need to display it in a code block. Below is the example JSON data:

 "grade": [
        {
            "alias": "G1",
            "id": "4d72868e-c46f-41d1-83a6-429a2421fd34",
            ...
            ...
            "updatedAt": "2021-06-11T15:19:07.387Z",
            "farmId": "703ab269-20f5-4dca-8687-e14de5f6a4cb"
    ]
}

And the desired output should look like this:

<br>
    <b-row>
    <b-col class="underline">My Grades</b-col>
    </b-row>
    <br>
    <div v-if="grades.length > 0">
    <b-card-group class="mb-4" v-for="grade in grades" :key="grade.id">
      <b-card :title="getTitle(grade)">
        <b-card-text class="list-card">
        

           
          {{getProperties(grade)}}
        
    

          <span style="float:right">
            <b-button
              class="mr-1"
              v-b-modal.modalConfirmDelete
              type="submit"
              variant="primary"
              size="sm"
            >
              <b-icon icon="map" size="is-small"></b-icon>
            </b-button>
            <b-button
              class="mr-1"
              type="reset"
              variant="danger"
              @click="actionDelete(grade.id)" 
              size="sm"
            >
              <b-icon icon="trash-fill" size="is-small"></b-icon>
            </b-button>
            <b-modal id="modalConfirmDelete" title="BootstrapVue">
                ddd
            </b-modal>
          </span>
        </b-card-text>
      </b-card>
    </b-card-group>

I have attempted different methods such as map and loops but have been unable to get the desired result due to varying property values in the JSON data. If someone could provide assistance on extracting only the properties, it would be greatly appreciated. Thank you.

Answer №1

Is this what you're seeking?

var jsonData = JSON.parse('{"grade":[{"alias":"G1","id":"4d72868e-c46f-41d1-83a6-429a2421fd34","name":"Grade 1","properties":{"size":"A1","dimensions":"2x2","maturity_weight":"150"},"createdAt":"2020-03-30T09:57:24.756Z","updatedAt":"2020-03-30T09:57:24.756Z","farmId":"703ab269-20f5-4dca-8687-e14de5f6a4cb"},{"alias":"G2","id":"62fbefef-3342-43aa-8ed3-ed2ff0ff7cd6","name":"Grade 2","properties":{"size":"A2","dimensions":"3x3","maturity_weight":"150"},"createdAt":"2020-11-22T13:29:42.461Z","updatedAt":"2020-11-22T13:29:42.461Z","farmId":"703ab269-20f5-4dca-8687-e14de5f6a4cb"},{"alias":"G3","id":"9ce20ee1-c197-4775-97cb-35998ce51d4b","name":"Grade 3","properties":{"size":"A3","dimensions":"4x4","maturity_weight":"150"},"createdAt":"2020-11-22T13:31:16.955Z","updatedAt":"2020-11-22T13:31:16.955Z","farmId":"703ab269-20f5-4dca-8687-e14de5f6a4cb"},{"alias":"G4","id":"83f6ff4b-ab75-4930-ab84-59763b24d435","name":"Grade 4","properties":{"size":"A4","dimensions":"4x4","maturity_weight":"150"},"createdAt":"2020-11-22T13:31:16.955Z","updatedAt":"2020-11-22T13:31:16.955Z","farmId":"703ab269-20f5-4dca-8687-e14de5f6a4cb"},{"alias":"G5","id":"8dea25be-93e3-4ab4-ae58-685e4ab05dbf","name":"Grade 5","properties":{"units":"gms","maxWeight":"170","minWeight":"100"},"createdAt":"2020-08-11T08:52:23.484Z","updatedAt":"2020-08-11T08:52:23.484Z","farmId":"703ab269-20f5-4dca-8687-e14de5f6a4cb"},{"alias":"G6","id":"85aa81e4-b428-44d5-9ee2-4215de6c8226","name":"Grade 6","properties":null,"createdAt":"2020-05-15T09:53:23.809Z","updatedAt":"2020-05-15T09:53:23.809Z","farmId":"703ab269-20f5-4dca-8687-e14de5f6a4cb"},{"alias":"SG","id":"f4cd4ec4-1b99-42b1-839b-cd18c54d1761","name":"some grade","properties":{"shape":"","units":"gms","dimension":"","maxWeight":"2","minWeight":"1"},"createdAt":"2021-06-11T15:10:39.102Z","updatedAt":"2021-06-11T15:10:39.102Z","farmId":"703ab269-20f5-4dca-8687-e14de5f6a4cb"},{"alias":"SO","id":"ef862161-e3e9-4b84-9164-178a600a15a8","name":"som","properties":{"shape":null,"units":"gms","dimension":null,"maxWeight":"3","minWeight":"2"},"createdAt":"2021-06-11T15:18:16.460Z","updatedAt":"2021-06-11T15:18:16.460Z","farmId":"703ab269-20f5-4dca-8687-e14de5f6a4cb"},{"alias":"AS","id":"4a4e1584-b0a7-4069-8851-0ee7f9e18267","name":"asdfadf","properties":{"shape":null,"units":"gms","dimension":null,"maxWeight":"sdf","minWeight":"asfd"},"createdAt":"2021-06-11T15:19:07.387Z","updatedAt":"2021-06-11T15:19:07.387Z","farmId":"703ab269-20f5-4dca-8687-e14de5f6a4cb"}]}');

new Vue({
  el: '#app',
  data() { return {
      grades: jsonData.grade,
    }
  },
});
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap@4/dist/css/bootstrap.min.css" /><link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.css" /><script src="//unpkg.com/vue@2/dist/vue.min.js"></script><script src="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.js"></script><script src="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue-icons.min.js"></script>

<div id="app">
  <b-row>
    <b-col class="underline">My Grades</b-col>
  </b-row>
  <br>
  <div v-if="grades.length > 0">
    <b-card-group class="mb-4" v-for="grade in grades" :key="grade.id">
      <b-card :title="grade.name">
        <b-card-text v-for="[key, value] in Object.entries(grade.properties != null ? grade.properties : {})" :key="key" class="list-card">
          {{ `${key}: ${value}` }}
          <span style="float:right">
              <b-button
                class="mr-1"
                v-b-modal.modalConfirmDelete
                type="submit"
                variant="primary"
                size="sm"
              >
                <b-icon icon="map" size="is-small"></b-icon>
              </b-button>
              <b-button
                class="mr-1"
                type="reset"
                variant="danger"
                @click="actionDelete(grade.id)" 
                size="sm"
              >
                <b-icon icon="trash-fill" size="is-small"></b-icon>
              </b-button>
              <b-modal id="modalConfirmDelete" title="BootstrapVue">
                  ddd
              </b-modal>
            </span>
        </b-card-text>
      </b-card>
    </b-card-group>
  </div>
</div>

The key change I introduced was replacing getProperties with a v-for, as showcasing multiple rows in the table mandates a new HTML element for each property in grade.properties.

For that v-for, I'm iterating on

Object.entries(grade.properties ?? {})
.

  • Object.entries() will yield a [key, value] array for each property in an object, enabling us to effortlessly display both.
  • grade.properties ?? {} simply returns an empty object {} when grade.properties is null or undefined. This prevents passing nullish values to Object.entries(), which throws an error if called with null/ undefined.
    • If the ?? operator isn't supported in your setup, then this alternate approach will suffice:
      grade.properties != null ? grade.properties : {}

(I also substituted getTitle(grade) with grade.name directly, but that's more of a personal preference.)

Answer №2

Understanding your requirements for the getProperties function is a bit challenging, but let me provide some assistance:

const grade1 = {"alias": "G1","id": "4d72868e-c46f-41d1-83a6-429a2421fd34","name": "Grade 1","properties": {"size": "A1","dimensions": "2x2","maturity_weight": "150"},"createdAt": "2020-03-30T09:57:24.756Z","updatedAt": "2020-03-30T09:57:24.756Z","farmId": "703ab269-20f5-4dca-8687-e14de5f6a4cb"};
const grade2 = {"alias": "G6","id": "85aa81e4-b428-44d5-9ee2-4215de6c8226","name": "Grade 6","properties": null,"createdAt": "2020-05-15T09:53:23.809Z","updatedAt": "2020-05-15T09:53:23.809Z","farmId": "703ab269-20f5-4dca-8687-e14de5f6a4cb"};
const grade3 = {"alias": "SG","id": "f4cd4ec4-1b99-42b1-839b-cd18c54d1761","name": "some grade","properties": {"shape": "","units": "gms","dimension": "","maxWeight": "2","minWeight": "1"},"createdAt": "2021-06-11T15:10:39.102Z","updatedAt": "2021-06-11T15:10:39.102Z","farmId": "703ab269-20f5-4dca-8687-e14de5f6a4cb"};
const grade4 = {"alias": "SO","id": "ef862161-e3e9-4b84-9164-178a600a15a8","name": "som","properties": {"shape": null,"units": "gms","dimension": null,"maxWeight": "3","minWeight": "2"},"createdAt": "2021-06-11T15:18:16.460Z","updatedAt": "2021-06-11T15:18:16.460Z","farmId": "703ab269-20f5-4dca-8687-e14de5f6a4cb"};

// The keyValString function is utilized within getProperties
function keyValString(obj) {
  // Reducing the output to a single string
  return Object.entries(obj).reduce((str, [key, value], index) => { // Iterating through each key and value
    if (value) { // Checking if value is not null or an empty string
      if (str) str += ", "; // Adding comma and space if there's existing text
      str += `${key}: ${value}`; // Including the key and value
    }
    return str; // Preserving the string for the next iteration
  }, "" /* <--- Beginning value for our reduce operation */);
}

function getProperties(grade) {
  // Checking if grade and grade.properties are not null before using keyValString(grade.properties), otherwise display "No properties on grade."
  return (grade && grade.properties && keyValString(grade.properties)) || "No properties on grade."; // Replacing the string with null would return null instead
}

console.log( getProperties(grade1) );
console.log( getProperties(grade2) );
console.log( getProperties(grade3) );
console.log( getProperties(grade4) );
.as-console-wrapper {min-height:100%} /* Adjusting console output format */

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are the steps to import a .obj 3D model into Three.js?

After incorporating your advice, here is the revised code: var renderer = new THREE.WebGLRenderer( { alpha: true } ); renderer.setSize( window.innerWidth, window.innerHeight ); element.appendChild( renderer.domElement ); var loader = new THREE.OBJLoader( ...

Need to convert the JSON values into keys

I have a JSON dataset that needs to be transformed. The current structure is as follows: [ { "name":"field1", "intValue":"1" }, { ...

Sending data to API using AngularJS Http Post

Upon clicking "Add new User", a modal pop-up will appear with a form containing a text field and a checkbox. However, upon clicking the create button, the data is not being posted to the API and the modal pop-up remains open without closing. I would like ...

Determine the data type of a string without needing to convert it

Can you determine if a value is numeric without casting it? For example, how can you differentiate between 'abc' and '123' without converting them to a specific data type? While visually apparent that 'abc' is not numeric, t ...

I require assistance in clearing the text field under specific circumstances

Incorporated in my webpage are text area controls that have been coded to automatically create a bullet-list when the user clicks on the text area or presses the 'ENTER' key. However, there is an issue - if the user clicks on the text area withou ...

Exploring the use of MediaSource for seamless audio playback

Currently working on integrating an audio player into my Angular web application by following a tutorial from Google Developers and seeking guidance from a thread on Can't seek video when playing from MediaSource. The unique aspect of my implementati ...

Issue with onClientClick not functioning properly when performing a jQuery function call

How can I make a jQuery form appear when an ASP.NET server-side button is clicked by the user? Currently, when I click on the button during runtime, the page reloads quickly without displaying the jQuery form. I am aiming to achieve a similar effect show ...

Unit tests are successful, but an error occurs stating "headers cannot be set after they have been sent."

Currently, I am working on writing unit tests for the API endpoints of my very first express app. I am using a data structure as a placeholder for a database and all the tests are passing successfully. However, I encountered an error in the console stating ...

Implementing Skeleton Loading Animation for VueJS Components during Firebase Data Retrieval

Considering implementing a skeleton loading component to display while waiting for data to load from firestore. The code snippet below shows my attempt at using suspense to fallback, but it seems to not work with the firebase API. Here is a portion of my t ...

Can mouseenter and mouseleave events be implemented in Chart.js?

Currently, I am using the onHover function on each pie to implement some scale/zoom effect. However, I would like to switch to using mouseenter and mouseleave. When there is a mouseenter event on a pie, it should enlarge with scale/zoom effect, and when th ...

The hunt is on for greater value within the index

My requirement is to check the text content of a box. If it matches any value stored in an ARRAY, then I have to execute a specific action. var ARRAY1 = ["Saab", "Volvo", "BMW"]; if (select[i].innerHTML.indexOf('ARRAY1') != -1){//code here} ...

Utilize jQuery to apply inline styles to dynamically created div elements

I am attempting to apply inline styles to a div using jQuery. The current state of the div, as seen in Firebug, is shown below: https://i.sstatic.net/rqhIc.jpg My goal is to retain the existing CSS while adding margin-left:0 and margin-right:0 to the cur ...

Utilize jQuery and AJAX to refresh functions after each AJAX call for newly added items exclusively

I have encountered an issue with my jQuery plugins on my website. Everything functions smoothly until I load new elements via AJAX call. Re-initializing all the plugins then causes chaos because some are initialized multiple times. Is there a way to only i ...

Using JavaScript to insert a value through AJAX

I'm currently working on a website that displays the value of a .TXT file, and here is the progress I've made so far: <script> $(document).ready(function() { $("#responsecontainer").load("info.txt"); var refreshId = setInterval(function( ...

Issues with Callbacks Inquiry

I'm struggling to understand how to implement callbacks in this scenario. Despite researching and reading explanations, I can't seem to grasp the concept. Below is a snippet of my code: function retrieveTransactionInfo(transactionUrl) { re ...

Encountering issues with upgrading Vue.js 2.5.2 with TypeScript

I am currently in the process of updating vue js to version 2.5.2 along with typescript 2.5.3. Below is my index.ts file: import Vue from 'vue' var app = new Vue({ el: '#app', data: { message: 'Hello Vue!' ...

Click on an Object within a modal window using JavaScript in Internet Explorer 8

I'm facing a strange issue with the SELECT object in a Modal Window. Within my HTML code, I have a button that opens a modal window when clicked. Inside this modal window, a JSP page is loaded. On this JSP page, there is a dropdown list created using ...

Using Facebook authentication in React Native

Currently developing a React Native app and aiming to incorporate Facebook login functionality. The back-end logic for user authentication is handled by an API in Node.js. Utilizing passport.js to enable users to log in using either Facebook or Email cre ...

Encountering a problem while deploying Vue to GitHub Pages due to issues with vue-router

I encountered some difficulties while deploying a Vue application built with vue-cli v3.0 to GitHub Pages. I utilized subtree to only deploy the dist folder to the gh-pages branch. Initially, the issue was that the assets were not being found, but I resolv ...

The Android JSON Parsing error occurs when a string cannot be converted to a JSONObject

Can someone assist me in parsing this JSON data from the following URL? Click here to access the JSON data When attempting to parse the URL, I encountered an exception: Error Message: 10-09 12:34:31.216: W/System.err(1856): org.json.JSONException: ...