Alexander Schmidt Alexander Schmidt - 2 months ago 7
Javascript Question

Building new JSON from existing one

I want to build an new JSON from existing one. The source has sections and rubrics that I no longer need for a listing. The new object called 'items' should have an array of the items. The final JSON should be sorted by attribute 'name' and look like

{
"items": [
{
"id": 10000006,
"name": "Boah"
},
{
"id": 10000013,
"name": "Gut"
},
{
"id": 10000003,
"name": "Ipsum"
},
{
"id": 10000001,
"name": "Lorem"
},
{
"id": 10000005,
"name": "Lorum"
},
{
"id": 10000004,
"name": "Name"
},
{
"id": 10000002,
"name": "Stet"
}
]
}


For building the new JSON I get this source:

{
"sections": [
{
"name": "FooBar",
"rubrics": [
{
"name": "Foo",
"items": [
{
"id": 10000001,
"name": "Lorem"
},
{
"id": 10000002,
"name": "Stet"
},
{
"id": 10000003,
"name": "Ipsum"
}
]
},
{
"name": "Bar",
"items": [
{
"id": 10000004,
"name": "Name"
},
{
"id": 10000005,
"name": "Lorum"
},
{
"id": 10000006,
"name": "Boah"
}
]
}
]
},
{
"name": "BlahBloob",
"rubrics": [
{
"name": "Bla",
"items": [
{
"id": 10000013,
"name": "Gut"
}
]
},
{
"name": "Bloob",
"items": [
{
"id": 10000014,
"name": "Name"
},
{
"id": 10000015,
"name": "Lorem"
}
]
}
]
}
]
}


What do you think? How can I do this with plain JavaScript or maybe TypeScript? Thanks for reading and have time for my question. And thanks for reply in advance.

Answer

Here you go. You just need to iterate over each rubric of each section of your source to get the items. At the end, sort your list of items by items, and you're done.

This example uses ES6 syntax, but it's easy to convert it to ES5 if needed.

function extractItems(source) {
  const items = [];

  for (const section of source.sections) {
    for (const rubric of section.rubrics) {
      items = items.concat(rubric.items);
    }
  }

  items.sort((a, b) => a.name.localeCompare(b.name));

  return { items };
}
Comments