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

175
Views
¿Cómo puedo hacer un condicional con retorno en un mapa sin salir de la función principal?

Mi objetivo es crear este objeto:

 { name: string, birthday: date }

por esta matriz:

 const dataArray = [ { "id": "name", "type": "string" }, { "id": "birthday", "type": "date" } ]

Entonces, creo un .map de la matriz, así:

 const inputsValues = {}; dataArray.map(item => { if(item.type === "date"){ inputsValues[item.id] = new Date(item.value); return; // this line is the problem } inputsValues[item.id] = item.value; });

¿Hay alguna opción para hacer una devolución en esta función sin usar else ?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

 const data = [ {id: "name", type: "string", value: "John"}, {id: "birthday", type: "date", value: "02.02.22"}, {id: "holiday", type: "date", value: "03.03.33"} ] const inputsValues = data // the "return" function - filters all non "date" items .filter(item => item.type != "date") // the map + inputsValue combination in one function .reduce((values, item) => ({[item.id]: item.value, ...values}), {}) console.log(inputsValues)

about 4 years ago · Juan Pablo Isaza Report

0

Usar el mapa solo para hacer un bucle en una matriz, sin usar la matriz devuelta, es un patrón anti. El mapa de funciones crea una nueva matriz aplicando la devolución de llamada dada a todos los valores de una matriz, es decir, dataArray . Este no es su caso porque quiere un objeto al final, no una matriz.

Para construir su estructura, debe usar, en su lugar, un for of loop, un forEach o Array.reduce() .

En caso de que solo necesite reducir su matriz a un solo objeto, reducir es la mejor opción:

 const dataArray = [ { "id": "name", "type": "string" }, { "id": "birthday", "type": "date" } ]; const obj = dataArray.reduce((carry, { id, type, value = '' }) => { carry[id] = type === 'date' ? new Date() : value; return carry; }, {}); // remember to initialize your carry, see reduce doc. console.log(obj); // My reduced object { name: '', date: 2022-...}
about 4 years ago · Juan Pablo Isaza Report

0

 const dataArray = [{ "id": "name", "type": "string" }, { "id": "birthday", "type": "date" } ] console.log( dataArray.reduce((acc, curr) => { acc[curr.id] = curr.type; return acc; }, {}) );

about 4 years ago · Juan Pablo Isaza 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!