Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

525
Views
JavaScript: ¿cómo puedo hacer referencia a un elemento en JSON como variable?

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?

about 4 years ago · Santiago Gelvez
3 answers
Answer question

0

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

about 4 years ago · Santiago Gelvez Report

0

Filtra tu entrada así

 let newFilteredArray = result.filter(item => { return item.id === 5; }; console.log(newFilteredArray[0];
about 4 years ago · Santiago Gelvez Report

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

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!