Convert nested arrays within an array of objects into a flat array

I have a unique challenge with an array of objects that I need to flatten into a new array of objects. The original structure is as follows:

const points = [
    {
        highlights: [
            {
                title: 'Title 1',
                description: 'Description 1',
                x: 111,
                y: 222,
            },
            {
                title: 'Title 2',
                description: 'Description 2',
                x: 111,
                y: 222,
            },
        ],
        width: 1108,
        height: 1528,
        relativePath: '/image_01.jpg',
    },
    {
        highlights: [
            {
                title: 'Title 3',
                description: 'Description 3',
                x: 199,
                y: 411,
            },
            {
                title: 'Title 4',
                description: 'Description 4',
                x: 213,
                y: 1132,
            },
        ],
        width: 1108,
        height: 1528,
        relativePath: '/image_02.jpg',
    },
];

The goal is to restructure each object in the 'highlights' array to have its own index, resulting in the following flat array:

[
    {
        title: 'Title 1',
        description: 'Description 1',
        x: 111,
        y: 222,
        width: 1108,
        height: 1528,
        relativePath: '/image_01.jpg',
    },
    {
        title: 'Title 2',
        description: 'Description 2',
        x: 111,
        y: 222,
        width: 1108,
        height: 1528,
        relativePath: '/image_01.jpg',
    },
    {
        title: 'Title 3',
        description: 'Description 3',
        x: 111,
        y: 222,
        width: 1108,
        height: 1528,
        relativePath: '/image_02.jpg',
    },
    {
        title: 'Title 4',
        description: 'Description 4',
        x: 111,
        y: 222,
        width: 1108,
        height: 1528,
        relativePath: '/image_02.jpg',
    },
];

I am considering using flatMap for this task, but I'm unsure how to preserve the other properties like width, height, relativePath. Any assistance would be greatly appreciated!

Answer №1

in simple terms:

const data = 
  [ { highlights: 
      [ { title: 'Title 1', description: 'Description 1', x: 111, y: 222 } 
      , { title: 'Title 2', description: 'Description 2', x: 111, y: 222 } 
      ] 
    , width        : 1108
    , height       : 1528
    , relativePath : '/image_01.jpg'
    } 
  , { highlights: 
      [ { title: 'Title 3', description: 'Description 3', x: 199, y: 411  } 
      , { title: 'Title 4', description: 'Description 4', x: 213, y: 1132 } 
      ] 
    , width        : 1108
    , height       : 1528
    , relativePath : '/image_02.jpg'
    } 
  ] 

const extractedData = data.reduce((result,{highlights,...otherProps})=>
  {
  highlights.forEach(hl=> result.push({...hl,...otherProps}))
  return result
  }
  ,[])

console.log(extractedData)

Answer №2

Check out this example implementing flatMap:

data.flatMap(item => 
    item.selections.flatMap(element => {
        let result = { ... item, ... element };
        delete result["selections"];
        return result;
    })
);

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

Unleashing the Power of Node Js: Retrieving File Data and Form Data in POST Requests

When sending form data values using Postman, you can utilize a NodeJS server in the backend to handle the POST request. Here is an example of how to structure your code: require('dotenv').config(); const express = require('express'); co ...

When utilizing an 'imported' asynchronous function, make sure to clean up the useEffect

Please do not mistake this for a duplicate. Despite my thorough search on various blogs and sources, I have yet to find a solution. My primary question is 'how can I address the error of react state change in unmounted component, and also cancel an a ...

Optimizing Node.js public js files based on different environments: A complete guide

Is there a way to customize public JavaScript files for different environments? Specifically, I want to change the socket.io connection location: For development: var socket = io.connect('http://localhost/chat'); For production: var socket = ...

Deducing hashtags from user-provided phrases by employing Java's list function

I am currently working on a project that involves allowing users to post comments and extracting specific words from those comments. For example: I enjoy #coding in #Python The desired output would be: #coding #Python Despite there being no apparent er ...

Tips for preventing the occurrence of numerous instances of braintree.setup in Angular

I am encountering an issue with a Braintree payment form displayed in a modal window: $scope.displayModalBraintree = function () { $scope.modal = 'modal_payment_form.html', $scope.$on('$includeContentLoaded', function () { ...

Is there a way to transfer the value from one directive to another directive template and access it in a different directive's scope?

I attempted to pass the directive attribute value to a template ID, which can then be used in another directive. Below is my index.html code: <my-value name="jhon"></my-value> Here is the JavaScript code: .directive('myValue',func ...

Having trouble with jquery onclick function not triggering

Having an unusual problem here. I've written a piece of code that allows users to generate and delete dynamic input elements. However, there seems to be an issue where clicking the remove button doesn't trigger the onclick event. <input typ ...

Why is the image auto-swapping script failing to display images frequently?

I have a script that is currently running to rotate between two different logos on my webpage. What I am attempting to achieve is for the page to load and then seamlessly transition from one image to the other without any blank space. Below is the code I ...

Can you offer advice on creating jasmine tests for an Angular controller and service similar to this?

I've been struggling with this issue for hours, mainly because I'm still new to Jasmine and AngularJS. The problem lies within my controller. angular.module('toadlane.controllers', []). controller('MainController', functi ...

Retrieve specific attributes in a nested eager loading sequelize query

I have a query to fetch information about shows from a database, along with details about the venue and bands involved. However, I am only interested in retrieving the names of the bands and the venue. The current code is pulling the entire record instea ...

exploring alternatives to ng-container in angular-4.x for selecting elements

Currently in my Angular 4.x project, I have a component using the Selector 'abc' as shown below: @Component({ selector: "Abc", templateUrl: "Abc.html", styleUrls: [ "Abc.css" ] }) However, the "Abc" tag is also present in the DOM, b ...

What is the reason behind the necessity of adding an extra slash when reloading the page and controller in AngularJS by using $location.path()?

In AngularJS, when you use $location.path() and pass the same URL as the current one, it does not reload the page and controller. However, if you add an extra slash at the end of the URL like this: $location.path('/currentURL/'); it forces a re ...

I encountered an issue with rendering static images when attempting to package my node-express app with pkg

Struggling to display an image from the public folder in my express app? I could use some guidance on configuring the path to properly render images or css files within the public folder when creating an executable file using pkg. Here's a snippet of ...

Is there a way to refresh CSS styles when the window width is adjusted?

Is there a way to refresh CSS styles when the window width changes? I attempted this method, but unfortunately it did not work as expected. A simple refresh (F5) helps to rectify the CSS tags. jQuery(function($){ var windowWidth = $(window).width(); ...

Tips on invoking a JSP and Servlet from JavaScript by passing in a parameter

Check out the code below for calling JavaScript functions: <td><input type="button" name="edit" value="Edit" onclick="editRecord(<%=rs.getString(1)%>);" ></td> <td><input type="button" name="delete" value="Delete" onclic ...

Could there be a more efficient method to enable support for all video formats?

I have a case statement in my video validation function that checks for specific file extensions of video formats. However, I am wondering if there is a shorter way to write the code in order to allow all video formats instead of creating a long list of al ...

Activate only one option group at a time

<select name="location"> <optgroup label="West Coast"> <option value="1">Los Angeles</option> <option value="2">San Francisco</option> <option value="3">Seattle</option> &l ...

Guide to redirecting to another page with parameters in React

After successfully integrating Stripe with React and processing a payment, I am trying to redirect to another page. await stripe .confirmCardPayment(CLIENT_SECRET, { payment_method: { card: elements.getElement(CardElement), ...

Angular http.get() recognizing when a call exceeds its timeout limit

I'm currently facing a challenge in detecting request timeouts with Angular http and promises. My code is designed to format API responses, but it fails to handle timeout errors effectively. Despite working when the API returns an error message, it do ...

The expected React component's generic type was 0 arguments, however, it received 1 argument

type TCommonField = { label?: string, dataKey?: string, required?: boolean, loading?: boolean, placeholder?: string, getListOptionsPromissoryCallback?: unknown, listingPromissoryOptions?: unknown, renderOption?: unknown, getOptionLabelFor ...