Converting data into dropdown

Hello everyone,
I have data that I received from a third party endpoint that looks like the JSON below.

{ 
   [...],
   "id": "prod_id",
   "attributes": {
         "size",
         "color"
   },
   "skus": {
        "data":[
               {
                 [...],
                  "attributes": {
                       "size": "Small",
                       "color": "green"
                  }
               },
              {
                [...],
                 "attributes": {
                       "size": "Small",
                       "color": "red"
                  }
              },
             {
                 "attributes": {
                       "size": "Medium",
                       "color": "red"
             }
        ]
    }
}

I was wondering how I would go about creating a drop-down for a user to select their attributes. (For example, the user can select a size that is small and a color that is green.) I am currently using blaze, but I would be fine with an answer in react. Thank you.

Something like this:

Template.attributeForm.onCreated(function () {
  this.data = new ReactiveVar({});

  // Replace with however data is retrieved
  getData(function (err, data) {
    this.data.set(data);
  }

  /**
   * Get a list of available attribute names
   *
   * @returns {Array} or false
   */
  this.getAttributeNames = function () {
    const data = this.data.get();
    return data && data.attributes;
  };

  /**
   * Get a list of attribute values by name
   *
   * @param {String} name - size, color
   *
   * @returns {Array} or false
   */
  this.getAttributeValues = function (name) {
    const data = this.data.get();
    if (!(data && data.skus && data.skus.data && data.skus.data.length)) {
      return false;
    }

    return data.skus.data.map((item) => {
      return item.attributes[name];
    });
  };
});

Template.attributeForm.helpers({
  attributeNames () {
    return Template.instance().getAttributeNames();
  },

  attributeValues (name) {
    return Template.instance().getAttributeValues(name);
  }
});

<template name="attributeForm">
  {{#each attributeNames}}
    <select name="{{.}}">
      <option value="">Select {{.}}</option>
      {{#each attributeValues .}}
        <option value="{{.}}">{{.}}</option>
      {{/each}}
    </select>
  {{/each}}
  <input type="submit" value="Add to cart" />
</template>
1 Like

Thanks. Appreciate it very much.:grinning: