Scott
Scott

Reputation: 21

Selecting an array item in handlebars by 'key'

Is it possible to select an array item in handlebars by a key/field name?

Say my array was like so

"MyVariables": [
    {
      "Key": "var1",
      "Value": 1
    },
    {
      "Key": "var2",
      "Value": 2
    },
    {
      "Key": "var3",
      "Value": 3
    }]

I know it can be done by index eg

{{MyVariables.2.Value}} 

However I would like something along the lines of

{{MyVariables.[Key == "var3"].Value}}

If it can't be done 'out of the box' does anyone know how it would be achieved with a helper?

I have searched high and low for this but cannot find a decent solution.

Thanks for reading.

Upvotes: 0

Views: 705

Answers (4)

Mauro López
Mauro López

Reputation: 109

A very simple way of do it is by change the struct of your array (MyVariables).

let MyVariables = [{
    "Key": "var1",
    "Value": 1
    },
    {
    "Key": "var2",
    "Value": 2
    },
    {
    "Key": "var3",
    "Value": 3
    }
];

let result = MyVariables.reduce(function(map, obj) {
    map[obj.Key] = obj.Value;
    return map;
}, {});    

console.log(result["var3"])

In that case, result have the main data of MyVariables list but structured different, who let access to the required value easily.

Upvotes: 1

Alen.Toma
Alen.Toma

Reputation: 4870

Here is a simple way using forEach

var arr= [
    {
      "Key": "var1",
      "Value": 1
    },
    {
      "Key": "var2",
      "Value": 2
    },
    {
      "Key": "var3",
      "Value": 3
    }]
    
    function value(key, keyValue, arr){
    var items= []
    arr.forEach((item)=>{
    if (item[key].indexOf(keyValue) != -1) // use indexOf or == its upp to you
        items.push(item)
    })
    return items;    
    }
    
    console.log(value("Key","var2", arr))

Upvotes: 0

Akshay Bande
Akshay Bande

Reputation: 2587

The better way is to use Array.prototype.reduce, use extra variable if you don't want to change the original array.

let MyVariables = [{
    "Key": "var1",
    "Value": 1
  },
  {
    "Key": "var2",
    "Value": 2
  },
  {
    "Key": "var3",
    "Value": 3
  }
];

// use different variable if you don't want to change MyVariables
MyVariables = MyVariables.reduce((acc, val) => {

  acc = acc ? acc : [];
  acc[val.Key] = val.Value;
  return acc;
}, [])

console.log(MyVariables["var1"]);
console.log(MyVariables["var2"]);
console.log(MyVariables["var3"]);

Upvotes: 0

apoteet
apoteet

Reputation: 784

You can accomplish this with Lodash's Find

Try {{_.find(MyVariables, ['Key', 'var3'])}}

Upvotes: 0

Related Questions