Simplifying a complex array of objects into a more streamlined version

Here's a glimpse of my array, which is quite extensive with over 1000 objects:

data = [
  {
    code: '3019476',
    _id: '60033f61-8a4e-4622-9731-decd07bc44e1',
    vendor: 'DKNY',
    info: ['array of objects'],
    tags: [
      { type: 1, label: 'dsfs' },
      { type: 2, label: 'thisOne' },
      { type: 3, label: 'sdas' },
    ],
  },
];

The goal here is to extract an array of objects where each object has one of the specified tag parameters.

Desired outcome:

data = [
  {contains all data from the original object, but with the tag { type: 1, label: 'dsfs' },
  {contains all data from the original object, but with the tag { type: 2, label: 'thisOne' },
  {contains all data from the original object, but with the tag { type: 3, label: 'sdas' }
]

Answer №1

When using the .reduce method:

const items = [
  {
    code: '3019476',
    _id: '60033f61-8a4e-4622-9731-decd07bc44e1',
    vendor: 'DKNY',
    info: ['array of objects'],
    tags: [ { type: 1, label: 'dsfs' }, { type: 2, label: 'thisOne' }, { type: 3, label: 'sdas' }  ]
  }
];

// looping through array items
const result = _.reduce(items, (accumulator, item) => {
  // extracting tags from each item
  const { tags=[] } = item;
  // iterating over tags
  _.forEach(tags, tag => {
    // creating a new object without the tags list
    const { tags, ...itemDetails } = _.cloneDeep(item);
    // adding an object with properties excluding tags + current tag to accumulator
    accumulator.push({ ...itemDetails, tag })
  });
  return accumulator;
}, []);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous"></script>

Alternatively, utilizing the .flatMap method:

const items = [
  {
    code: '3019476',
    _id: '60033f61-8a4e-4622-9731-decd07bc44e1',
    vendor: 'DKNY',
    info: ['array of objects'],
    tags: [ { type: 1, label: 'dsfs' }, { type: 2, label: 'thisOne' }, { type: 3, label: 'sdas' }  ]
  }
];

// looping through array items
const result = _.flatMap(items, item => {
  // extracting tags from each item
  const { tags=[] } = item;
  // returning array of objects with different tags
  return _.map(tags, tag => {
    const { tags, ...itemDetails } = _.cloneDeep(item);
    return { ...itemDetails, tag };
  });
});

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous"></script>

Answer №2

To simplify the data structure, you can map both the outer and inner arrays.

const
    list = [{ code: '3019476', _id: '60033f61-8a4e-4622-9731-decd07bc44e1', vendor: 'DKNY', info: ['array of objects'], tags: [{ type: 1, label: 'dsfs' }, { type: 2, label: 'thisOne' }, { type: 3, label: 'sdas' }] }],
    updatedList = list.flatMap(({ tags, ...rest }) => tags.map(tagData => ({ ...rest, tagData })));

console.log(updatedList);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using XOAuth2 authentication with Gmail to provide client ID, client secret, and refresh token for sending emails through Node Mail

I have integrated nodemailer with my NodeJS server and successfully set up the following credentials using one of my email addresses: - Client ID - Client Secret - Refresh Token However, I am currently facing an issue due to Google changing their confi ...

Problem installing ext-gen in ExtJS 7 Community Edition

After successfully logging into the sencha NPM repo with this command: npm login --registry=https://sencha.myget.org/F/community/npm/ --scope=@sencha The response confirmed my login status: Logged in as stevemc to scope @sencha on https://sencha.myget.org ...

Guarding Vue.js routes when navigating based on asynchronous authentication state requests

I have integrated Firebase for authentication in my Vue.js application. The main (main.js) Vue component handles the authentication logic as follows: created() { auth.onAuthStateChanged((user) => { this.$store.commit('user/SET_USER&apo ...

Tips for updating mongoose user data with associated posts that share the same user id

As I dive into building my inaugural MERN application, a particular issue has arisen. The posts within the application contain the user id information: { "reward": { ... }, "_id": "5eb2d90d7d56c415cc4d5f97", "user": "5eabbb85b8814 ...

Using asynchronous methods to import a Node.js module

I am attempting to asynchronously load 2 modules due to some issues I encountered. The first module loads and creates a database connection (which takes some time) The second module uses the created connection to handle sessions using express-sessions. ...

Why isn't $.post functioning properly in any instance?

I've been experiencing issues with my $.post calls throughout my code. Despite not sending requests to different domains, everything is localhosted. My Mac OS X 10.8 automatically defined my localhost alias as ramon.local, and I'm trying to make ...

Can you generate an image of text using unique unicode characters?

I am looking to create and display an image of text. Currently, I am experimenting with text2png: text2png('this string', {font: '14px Courier', bgColor: 'white'}) However, it appears that text2png is unable to handle unico ...

Issue with history.go(-1) method malfunctioning on dropdown menu

Currently, I am facing an issue with the functionality of my back button using history.go(-1) in conjunction with a dropdown selection. Despite the source code displaying the original selected value, the UI is showing a previous value. When clicking on t ...

Incorporating a GLTF Model in a Basic React Three Fiber Environment

I am attempting to incorporate a model with diffuse and bump textures into a basic scene using react 3 fiber. Despite my best efforts, I can't seem to figure out what mistake I might be making. You can view the sandbox here: https://codesandbox.io/s ...

Delete JavaScript functions and events from memory once the JavaScript code has been removed from the HTML file

I am encountering a situation with my website where popups loaded via ajax also load JavaScript code, which I want to remove when the popup is closed. The main site code looks like this: <body> ... <div id="popup" style="display:none"> < ...

Basic application - angular has not been declared

I'm currently diving into the realm of javascript and angularjs, following along with the tutorials on . After setting up a basic IntelliJ javascript project, I created two essential files: index.html <!DOCTYPE html> <html lang="en"> ...

"Vue's watch method seems to be failing to properly filter through

The filter functionality within a Vue watched function doesn't appear to be functioning as expected. Despite returning false for the E: object and true for all other items, the E: object remains in the array when it should have been removed. Below is ...

Issue with Bootstrap 4 Navbar collapsing and not expanding again

Help needed! My navigation bar collapses when the window is resized, but clicking on the hamburger icon does not open it back up. I have included my code below. Can someone please provide guidance on how to expand the collapsed navbar? <html lang=&quo ...

Creating dynamic elements and mounting them on the fly using VueJS

The Dilemma I have devised a sleek covering for jQuery DataTables in VueJS as shown below: <template> <table ref="table" class="display table table-striped" cellspacing="0" width="100%"> <thead> <tr> ...

JavaScript: retrieving undefined value from a text element

My goal is to retrieve the text entered into each textbox by querying and looping through their ID tags. However, when I attempt to print what I have retrieved, it always displays "undefined". Seems like your post consists mostly of code: </h ...

PHP mutation of strings

Consider an array structured like this: $array = Array(Array('a' => 'a', 'x' => $something)); The variable $something can take on these formats: 1-3, 1,3, or 1-3, 2-5. I want to convert the variable $array to: Scenari ...

Is it necessary to utilize process.env in node.js?

In my project, there is a .env file containing the following: ABC='abc' While in my app.js I can access the value abc using process.env.ABC, how can I require it to be used in my models' files? Attempting to use process.env.ABC in my model ...

I'm working on generating a numerical pattern that starts with an input number, decreases, and then increases back up to the original number one digit at a time

I am attempting to create a recursive function that can produce a pattern similar to the example below. cascade(12345) //should print 12345 1234 123 12 1 12 123 1234 12345 While I have managed to achieve the descending part, I am now facing difficulty in ...

Developing a universal.css and universal.js file for a custom WordPress theme

I have developed a custom WordPress theme with an extensive amount of code. To manage the numerous style and script files, I have segmented them into multiple individual files. To integrate all these files into my template, I utilized the following code w ...

What is the best way to calculate the average of a specific subset of an array and then save the final result in a

I need assistance with a task involving an array called fftArray[64]. I am aiming to compute the average of certain chunks within this array and store them in another array named frequencyBar[8]. Calculating the overall average of fftArray is manageable us ...