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

218
Views
Flatten array of items into the middle of another array

I have an array like so

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

How can I flatten the unwrap object to get the following output?

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

I thought I could do something like this:

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

However the ...s don't work as a return value.

I have come up with the somewhat clunky using a second array like so:

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

You can rely on flatMap:

items.flatMap((x) => {
  if (!x.unwrap) {
    return x;
  }

  return x.items;
});
about 4 years ago · Juan Pablo Isaza Report

0

flatMap is what you need.

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

Another way using 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);

Since obj.items won't exist on the regular objects, we can use the || operator to get the desired items, then concat those to the final array.

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!