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

199
Views
Obtenga un objeto JavaScript de una matriz de objetos por valor de propiedad

Digamos que tengo una matriz de cuatro objetos:

 var jsObjects = [ {a: 1, b: 2}, {a: 3, b: 4}, {a: 5, b: 6}, {a: 7, b: 8} ];

¿Hay alguna manera de obtener el tercer objeto ( {a: 5, b: 6} ) por el valor de la propiedad b , por ejemplo, sin un bucle for...in ?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Filter la matriz de objetos, cuya propiedad coincide con el valor, devuelve la matriz:

 var result = jsObjects.filter(obj => { return obj.b === 6 })

Consulte los documentos de MDN en Array.prototype.filter()

 const jsObjects = [ {a: 1, b: 2}, {a: 3, b: 4}, {a: 5, b: 6}, {a: 7, b: 8} ] let result = jsObjects.filter(obj => { return obj.b === 6 }) console.log(result)

Find el valor del primer elemento/objeto en la matriz; de lo contrario, se devuelve undefined .

 var result = jsObjects.find(obj => { return obj.b === 6 })

Consulte los documentos de MDN en Array.prototype.find()

 const jsObjects = [ {a: 1, b: 2}, {a: 3, b: 4}, {a: 5, b: 6}, {a: 7, b: 8} ] let result = jsObjects.find(obj => { return obj.b === 6 }) console.log(result)

over 4 years ago · Santiago Trujillo Report

0

jsObjects.find(x => xb === 6)

Desde MDN:

El método find() devuelve un valor en la matriz, si un elemento de la matriz satisface la función de prueba proporcionada. De lo contrario, se devuelve undefined .


Nota al margen: los métodos como find() y las funciones de flecha no son compatibles con los navegadores más antiguos (como IE), por lo que si desea admitir estos navegadores, debe transpilar su código usando Babel .

over 4 years ago · Santiago Trujillo Report

0

No sé por qué estás en contra de un bucle for (presumiblemente te refieres a un for loop , no específicamente for..in ), son rápidos y fáciles de leer. De todos modos, aquí hay algunas opciones.

En bucle:

 function getByValue(arr, value) { for (var i=0, iLen=arr.length; i<iLen; i++) { if (arr[i].b == value) return arr[i]; } }

.filtrar

 function getByValue2(arr, value) { var result = arr.filter(function(o){return ob == value;} ); return result? result[0] : null; // or undefined }

.para cada

 function getByValue3(arr, value) { var result = []; arr.forEach(function(o){if (ob == value) result.push(o);} ); return result? result[0] : null; // or undefined }

Si, por otro lado, realmente quiso decir for..in y quiere encontrar un objeto con cualquier propiedad con un valor de 6, entonces debe usar for..in a menos que pase los nombres para verificar.

Ejemplo

 function getByValue4(arr, value) { var o; for (var i=0, iLen=arr.length; i<iLen; i++) { o = arr[i]; for (var p in o) { if (o.hasOwnProperty(p) && o[p] == value) { return o; } } } }
over 4 years ago · Santiago Trujillo 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!