Search code examples
javascriptjsonvue.jsobjectbootstrap-vue

How to loop through json obejct and return keys and values if they are all different or even null? Vue, Javascript


need to go through a JSON object which might or might not have properties fields it can be null or it can have 10 different ones I then need to print it in a code block, the JSON data is here:

 "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"
        }
    ]
}

And return values such as:

<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 tried a few things like map, this below and join and nothing works because the properties in the json are all diff, tried for loop with length too.

getProperties(grade) {
      if (grade) {
         for (const [key, value] of Object.entries(grade)) {
            return `key: ${key}, value: ${value}`
          }
          
         }
      }
    },

Only need properties, thanks in advance


Solution

  • Is this what you're looking for?

    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 main change I made was to replace getProperties with a v-for, since displaying multiple rows in the table requires a new HTML element for each property in grade.properties.

    For that v-for, I'm looping on Object.entries(grade.properties ?? {}).

    • Object.entries() will return a [key, value] array for each property in an object, allowing us to easily display both.
    • grade.properties ?? {} just returns an empty object {} when grade.properties is null or undefined. This avoids giving nullish values to Object.entries(), which throws an error if you call it with null/ undefined.
      • If the ?? operator isn't supported in your setup, then this will suffice just as well:
        grade.properties != null ? grade.properties : {}

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