Skip to content Skip to sidebar Skip to footer

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 d

Solution 1:

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"}]}');

newVue({
  el: '#app',
  data() { return {
      grades: jsonData.grade,
    }
  },
});
<linktype="text/css"rel="stylesheet"href="//unpkg.com/bootstrap@4/dist/css/bootstrap.min.css" /><linktype="text/css"rel="stylesheet"href="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.css" /><scriptsrc="//unpkg.com/vue@2/dist/vue.min.js"></script><scriptsrc="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.js"></script><scriptsrc="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue-icons.min.js"></script><divid="app"><b-row><b-colclass="underline">My Grades</b-col></b-row><br><divv-if="grades.length > 0"><b-card-groupclass="mb-4"v-for="grade in grades":key="grade.id"><b-card:title="grade.name"><b-card-textv-for="[key, value] in Object.entries(grade.properties != null ? grade.properties : {})":key="key"class="list-card">
          {{ `${key}: ${value}` }}
          <spanstyle="float:right"><b-buttonclass="mr-1"v-b-modal.modalConfirmDeletetype="submit"variant="primary"size="sm"
              ><b-iconicon="map"size="is-small"></b-icon></b-button><b-buttonclass="mr-1"type="reset"variant="danger"
                @click="actionDelete(grade.id)"size="sm"
              ><b-iconicon="trash-fill"size="is-small"></b-icon></b-button><b-modalid="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.)

Solution 2:

I have trouble working out what you want from the getProperties function, but does this help?

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

// this function is used in getPropertiesfunctionkeyValString(obj) {
  // reduce the output to one stringreturnObject.entries(obj).reduce((str, [key, value], index) => { // for each key and valueif (value) { // if value is not null or an empty stringif (str) str += ", "; // if there is already text, add a comma and space
      str += `${key}: ${value}`; // add on the key and value
    }
    return str; // keep the string for the next loop
  }, ""/* <--- this empty string is the start value for our reduce operation */);
}

functiongetProperties(grade) {
  // if grade not null, and grade.properties not null, use keyValString(grade.properties) else use "No properties on grade."return (grade && grade.properties && keyValString(grade.properties)) || "No properties on grade."; // to instead return null, just replace the string with null
}

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

Post a Comment for "How To Loop Through Json Obejct And Return Keys And Values If They Are All Different Or Even Null? Vue, Javascript"