-2

There is an array of JSONs :

var a = [ {id:1, latlong:[...]} , {id:2, latlong:[...]} , ... ];

How to get the JSON element which key id equals 2 for example ?

pheromix
  • 16,775
  • 24
  • 79
  • 150
  • Possible duplicate: https://stackoverflow.com/questions/2722159/how-to-filter-object-array-based-on-attributes – seasick Oct 14 '19 at 15:07
  • Please read: [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/a/261593/3082296) – adiga Oct 14 '19 at 15:11

3 Answers3

0

Check out the .filter method.

var a = [ {id:1, latlong:[...]} , {id:2, latlong:[...]} , ... ];
console.log(a.filter((item) => item.id === 2));
seasick
  • 448
  • 1
  • 4
  • 15
0

You can use array filter which will return an array of objects. Then use index (example [0] in this code) to retrieve the first object

var a = [{
  id: 1,
  latlong: ''
}, {
  id: 2,
  latlong: ''
}];

let newVal = a.filter(e => e.id === 2)[0];
console.log(newVal)
brk
  • 46,805
  • 5
  • 49
  • 71
0

To find a single entry, there's the .find method:

const a = [ {id:1, latlong:[...]} , {id:2, latlong:[...]} , ... ];
const el = a.find((item) => item.id === 2);
console.log(el);
tiagodws
  • 1,175
  • 15
  • 18