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

193
Views
Is there a way to reduce a nested json by extracting only certain values?

I have the following, nested, json structure:

{
  element: "a",
  items: ["l1", "l2"],
  children: [{
    element: "b",
    children: [{
      element: "c",
      items: ["l3"]
    }, {
      element: "b",
      child: {
        element: "c",
        items: ["l4"]

      }
    }

Basically:

  • An "element" contains a name, a list of items, and a list of children being an "element" themselves
  • The items list can be missing

I'd like to process this json to get a flat array containing all the items:

const finalArray = parse(json); //returns ["l1","l2","l3","l4"]

Is there any elegant way to achieve this with mapping/filter functions?

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

0

const getItems = (acc = [], { items = [], child = {}, children = [] }) => 
  [
    ...acc, 
    ...items, 
    ...(child?.items || []),
    ...(children.length ? children.reduce(getItems, acc) : [])
  ];

const data = { 
  element:"a",
  items: ["l1","l2"],
  children: [ 
    {
      element: "b",
      children: [
        { element: "c", items: ["l3"] },
        { element: "b", child: { element: "c", items: ["l4"] } }
      ]
    }
  ]
}
console.log( getItems([], data) );

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!