0

I have a JavaScript array myArray = [{'id':'73','data':'SampleData 1'},{'id':'45','data':'SampleData 2'}];

By providing the id of this array as 45 how can i get the SampleData 2 as data.

Please help.Thanks in advance.

gilzon.me
  • 109
  • 2
  • 6
  • Use a for loop and an if statement? Do you know how to loop through an array? – qxz Nov 26 '16 at 01:40
  • What have you tried? There are many ways to do this, and libraries like [underscore](http://underscorejs.org/) provide methods to do exactly what you are asking. – chazsolo Nov 26 '16 at 01:41

2 Answers2

0

This should do it for you. Test the snippet and you will see the alert run. There are better ways to do this, but this method is simple and doesn't require anything but javascript.

data = [{"id": 45, "thing": "asdf"}, {"id": 32, "thing": "jkl"}];

for (i=0; i<data.length; i++) {
  if (data[i].id == 45) {
    alert("Found the object with id of 45, alerting 'thing' property");
    alert(data[i].thing);
  }
}
Dylan Hamilton
  • 662
  • 4
  • 14
0

By filtering the array for the ID you want, you'll get back an array with only objects matching the filter.

const [myItem] = myArray.filter(item => item.id === 45);

In the above code, myItem will be {'id':'45','data':'SampleData 2'}. You could go a step further and do:

const [{ data: myItemsData }] = myArray.filter(item => item.id === 45);

In this situation, myItemsData will be 'SampleData 2'.

As @torazaburo points out, you can use:

const { data: myItemsData } = myArray.find(item => item.id === 45);
David
  • 1,326
  • 9
  • 16
  • Why are you using `filter` instead of `find`? –  Nov 26 '16 at 03:09
  • @torazaburo old habit. [Array#filter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) has compatibility back further than [Array#find](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) – David Nov 26 '16 at 03:11
  • 1
    Any environment supporting destructuring assignment will have `find`. –  Nov 26 '16 at 03:11
  • Definitely. Just that i've been using filter for much longer than find, so I tend to think of it first. You're correct, however. – David Nov 26 '16 at 03:14