Finding Product Vartiant

Some code for selecting the right product variant for an online store.

by kshep92

JavaScript

const product = {
  id: 1,
	name: "Google Pixel 2",
	price: 179.00,
	currency: "USD",
	options: [
	  { id: 2, name: "Colour", values: [
		    {id: 3, value: "Just Black", photo_id: "..."},
				{id: 4, value: "Kinda Blue", photo_id: "..."},
				{id: 5, value: "White", photo_id: "..."}
		  ]
		},
	  { id: 1, name: "Capacity", values: [
		    {id: 1, value: "64GB"},
				{id: 2, value: "128GB"},
				{id: 9, value: "256GB"}
	    ] 
	  },
		{ id: 3, name: "Network", values: [
		    {id: 6, value: "Unlocked"},
				{id: 7, value: "bMobile"},
				{id: 8, value: "Digicel"}
		  ]
		}
	],
	variants: [
	  {id: 1, price: 189.00, amt_in_stock: 4, props: {
		    "Colour": "White",
				"Capacity": "64GB",
				"Network": "Unlocked"
		  }
		},
    {id: 2, price: 189.00, amt_in_stock: 3, props: {
		    "Colour": "Just Black",
				"Capacity": "64GB",
				"Network": "Unlocked"
		  }
		},
    {id: 2, price: 189.00, amt_in_stock: 0, props: {
		    "Colour": "White",
				"Capacity": "128GB",
				"Network": "Unlocked"
		  }
		}
	]
}

const query = {}

function stringify(props) {
  const values = [];
  for(let key in props) {
    values.push(props[key])
  }
  return values.join('-');
}

// Set up the default query object
for(let i = 0; i < product.options.length; i++) {
  let _option = product.options[i];
  let _name = _option.name;
  let _value = _option.values[0].value;
  query[_name] = _value
}

// Assign a hash to each variant
for(let i=0; i<product.variants.length; i++) {
  const variant = product.variants[i];
  variant['hash'] = stringify(variant.props);
}

// Lookup a variant by option and value
function findVariant(key, val) {
  if(key != undefined && val != undefined) {
    query[key] = val;
  }
 const results = product.variants.find(v => {
   console.log(v.hash, stringify(query));
   return v.hash == stringify(query);
  });
  return results != undefined ? results : null;
}

const black64Gb = findVariant();

const white64Gb = findVariant('Colour', 'White');

console.log(black64Gb,...