Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find a value in a multidimensional array if I know another?

I have a multidimensional array and uses jQuery. I know shortname, how do I get the conversionSI and put the result in a variable, console.log or something else? Or could my array look in a better way (as I want it to be as quick as possible).

My Array

var UnitArray = [ {
 name : "liter",
 shortName : "l",
 unitType : "volym",
 country : "sv",
 conversionSI : 1
 }, {
 name : "deciliter",
 shortName : "dl",
 unitType : "volym",
 country : "sv",
 conversionSI : 0.1
 }, {
 name : "centiliter",
 shortName : "cl",
 unitType : "volym",
 country : "sv",
 conversionSI : 0.01
 }];

E.g I know the shortnames "cl" and "dl" and want to use the conversionSI from them in a calculation.

like image 852
Anders Avatar asked Dec 30 '25 08:12

Anders


1 Answers

You can create a function like this DEMO

var getConversion = function(el) {
  for (var i = 0; i < UnitArray.length; i++) {
    var obj = UnitArray[i];
    if (obj.shortName == el) return obj.conversionSI;
  }
}

console.log(getConversion('cl'));

Updated function that returns array with results Demo

like image 125
Nenad Vracar Avatar answered Jan 01 '26 00:01

Nenad Vracar