Considere que tengo la siguiente variable:
var result = { "Items": [ { "location": "New York", "visible": false, "destinations": [ 4, 3, 5 ], "id": 3, "coordinates": { "lng": -74.17, "lat": 40.68 } },{ "location": "Madrid", "visible": false, "destinations": [ 0, 4 ], "id": 0, "coordinates": { "lng": -3.56, "lat": 40.49 } }, { "location": "Los Angeles", "visible": false, "destinations": [ 4, 3, 5 ], "id": 5, "coordinates": { "lng": -118.4, "lat": 33.94 } } ] };
Si quiero hacer referencia a Los Ángeles, haría lo siguiente y funciona muy bien:
console.log(result.Items[2]);
¿Qué pasa si no sé el pedido pero sé su id (5). ¿Cómo puedo referenciarlo por su ID?
No puede hacer referencia a él directamente, pero puede usar alguna función de Javascript en la matriz para encontrarlo, como:
result.Items.find(x => x.id == 5);
Referencia: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
Filtra tu entrada así
let newFilteredArray = result.filter(item => { return item.id === 5; }; console.log(newFilteredArray[0];
Tu puedes hacer:
var result = { "Items": [ { "location": "New York", "visible": false, "destinations": [ 4, 3, 5 ], "id": 3, "coordinates": { "lng": -74.17, "lat": 40.68 } }, { "location": "Madrid", "visible": false, "destinations": [ 0, 4 ], "id": 0, "coordinates": { "lng": -3.56, "lat": 40.49 } }, { "location": "Los Angeles", "visible": false, "destinations": [ 4, 3, 5 ], "id": 5, "coordinates": { "lng": -118.4, "lat": 33.94 } } ] }; var array = JSON.parse(JSON.stringify(result)); for (i = 0; i <= array.Items.length - 1; i++) { if (array.Items[i].id == 5) { console.log(array.Items[i]) } }