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?

2
  • Do you know how to loop over an array? Commented Aug 3, 2016 at 8:29
  • You could use a Map, see for example stackoverflow.com/questions/4246980/… . Commented Aug 3, 2016 at 8:31

5 Answers 5

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
         }
    }
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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);
  }
}

Comments

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.

Comments

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';
})

1 Comment

arr.map(function(item){ return item.price; });

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.