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