2

I have a data structure like below...

[
  {name: "coke",  price:"10"},
  {name: "sprit", price: "20"}
]

My question is how do I get the price based on its name? for example, how do get coke price?

Dennis
  • 3,962
  • 7
  • 26
  • 44
Dreams
  • 8,288
  • 10
  • 45
  • 71

5 Answers5

2

Loop over the array using any looping method you like (such as for, Array.prototype.forEach, or Array.prototype.filter) and test the value of the name property of each object until you find the one you want. Then get the value property of it.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
2

can do it with the loop function

    var dataArr = [
      {name: "coke",  price:"10"},
      {name: "sprit", price: "20"}
    ];

    for(var i=0;i<dataArr.length;i++){
         if(dataArr[i].name == "coke"){
             console.log(dataArr[i].price); // prints 10
         }
    }
Özgür Ersil
  • 6,909
  • 3
  • 19
  • 29
2

Just loop through the array and get the object property.

var arr = [{name: "coke",  price:"10"},{name: "sprit", price: "20"}];

for (var i = 0, len = arr.length; i < len; i++) {
  if(arr[i].name === "coke"){
       console.log(arr[i].price);
  }
}
Thalaivar
  • 23,282
  • 5
  • 60
  • 71
0

Please try:

(arr.find(function(item){ return item.name === 'coke'}) || {}).price;

or you can find all items named "coke":

arr.filter(function(item){
    return item.name === 'coke';
})
Markus-ipse
  • 7,196
  • 4
  • 29
  • 34
Carson Liu
  • 86
  • 3
0
var data = [{
  name: "coke",
  price: "10"
}, {
  name: "sprit",
  price: "20"
}];

function getValue(data, name) {
  for (let i = 0; i < data.length; i++) {
    if (data[i].name === name) {
      return data[i].price;
    }
  }
}

var value = getValue(data, 'coke');
alert(value);

https://jsfiddle.net/ej5ofsxm/

You can loop through the array and get price based on name.

James
  • 1,436
  • 1
  • 13
  • 25