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

209
Views
Aplane la matriz de elementos en el medio de otra matriz

tengo una matriz asi

 let items = [ {name: "1"}, {name: "2"}, {name: "3"}, {unwrap: true, items: [ {name: "4"}, {name: "5"}, {name: "6"}, ] }, {name: "7"}, ]

¿Cómo puedo aplanar el objeto desenvuelto para obtener el siguiente resultado?

 items = [ {name: "1"}, {name: "2"}, {name: "3"}, {name: "4"}, {name: "5"}, {name: "6"}, {name: "7"}, ]

Pensé que podría hacer algo como esto:

 items.map(item => { if(item.hasOwnProperty("unwrap")){ return ... item.items } return item })

Sin embargo, los ... s no funcionan como valor de retorno.

Se me ocurrió algo torpe usando una segunda matriz así:

 let output = [] items.forEach((item) => { if (!item) { return; } if (item.hasOwnProperty("unwrap")) { return output.push(...item.contents); } return output.push(item); });
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Puedes confiar en flatMap :

 items.flatMap((x) => { if (!x.unwrap) { return x; } return x.items; });
about 4 years ago · Juan Pablo Isaza Report

0

flatMap es lo que necesitas.

 const items=[{name:"1"},{name:"2"},{name:"3"},{unwrap:!0,items:[{name:"4"},{name:"5"},{name:"6"}]},{name:"7"}]; const result = items.flatMap(item => { if (item.hasOwnProperty('unwrap')) { return item.items; } return item; }); console.log(result);

about 4 years ago · Juan Pablo Isaza Report

0

Otra forma de usar reduce()

 let items = [{name: "1"}, {name: "2"}, {name: "3"}, {unwrap: true, items: [{name: "4"}, {name: "5"}, {name: "6"}, ] }, {name: "7"}, ]; const res = items.reduce((p, c) => p.concat(c.items || c), []); console.log(res);

Dado que obj.items no existirá en los objetos regulares, podemos usar el || operador para obtener los elementos deseados, luego concat a la matriz final.

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!