Home > Web Front-end > JS Tutorial > How to Nest an Array of Objects Based on Key Values for Optimized Rendering?

How to Nest an Array of Objects Based on Key Values for Optimized Rendering?

DDD
Release: 2024-12-04 11:29:10
Original
1138 people have browsed it

How to Nest an Array of Objects Based on Key Values for Optimized Rendering?

Grouping Array of Objects with Nesting Keys

Problem:

Given an array of objects, the task is to reorganize them into a format optimized for rendering by creating nested structures based on specific key values.

Example:

Input Array:

[
  {
    tab: 'Results',
    section: '2017',
    title: 'Full year Results',
    description: 'Something here',
  },
  {
    tab: 'Results',
    section: '2017',
    title: 'Half year Results',
    description: 'Something here',
  },
  {
    tab: 'Reports',
    section: 'Marketing',
    title: 'First Report',
    description: 'Something here',
  }
]
Copy after login

Desired Output:

[
  {
    tab: 'Results',
    sections: [
      {
        section: '2017',
        items: [
          { 'item that belongs here' },
          { ... }
        ]
      }
    ]
  },
  {
    tab: 'Reports',
    sections: [
      {
        section: 'Marketing',
        items: [
          { ... },
          { ... }
        ]
      }
    ]
  }
]
Copy after login

Solution:

This transformation can be achieved using a combination of lodash functions _.map and _.groupBy.

function groupAndMap(items, itemKey, childKey, predic) {
  return _.map(_.groupBy(items, itemKey), (obj, key) => ({
    [itemKey]: key,
    [childKey]: (predic && predic(obj)) || obj
  }));
}
Copy after login

To nest the data as desired, apply groupAndMap recursively.

const output = groupAndMap(items, "tab", "sections", arr =>
  groupAndMap(arr, "section", "items")
);
Copy after login

This solution accomplishes the objective of grouping and nesting the array of objects based on specific key values.

The above is the detailed content of How to Nest an Array of Objects Based on Key Values for Optimized Rendering?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template