What is the best way to extract data from a nested array within an array of objects and transfer it to a separate array without altering its nested arrangement?

I have a collection of different objects stored in an array. Each object within the main array contains another array with specific details like this:

const data =
    [
        {
            id: 1, name: "Jack", interests: 
            [
                {id: 9, name: "basketball"},
                {id: 8, name: "art"}
            ]
        },
        {
            id: 2, name: "Jenny", interests: 
            [
                {id: 7, name: "reading"},
                {id: 6, name: "running"}
            ]
        }
    ];

My goal is to combine all nested arrays into one new array structured like this:

newArray = 
    [
        [{id: 9, name: "basketball"}, {id: 8, name: "art"}],
        [{id: 7, name: "reading"},{id: 6, name: "running"}]
    ];

Even though I tried pushing the data to a new array, it becomes unnested when executed like this:

data.map(v => { v.interests.map(x => { newArray.push({name: x.name, id:x.id}) }) })

Is there a way I can transfer the nested structure of the interests data to the new array?

Answer №1

To get the interests of each item, simply use the .map method:

const data=[{id:1,name:"Jack",interests:[{id:9,name:"basketball"},{id:8,name:"art"}]},{id:2,name:"Jenny",interests:[{id:7,name:"reading"},{id:6,name:"running"}]}]
const mapped = data.map(({ interests }) => interests);
console.log(mapped);

It is important to note that when using .map, you should not create a new array beforehand and then use push; instead, utilize return for each new array item (or rely on arrow function's implicit return). Avoid treating .map as forEach.

If you need to map the interests array and also transform the objects within it, consider using a nested map like this:

const data=[{id:1,name:"Jack",interests:[{id:9,name:"basketball",foo:'bar'},{id:8,name:"art",foo:'bar'}]},{id:2,name:"Jenny",interests:[{id:7,name:"reading",foo:'bar'},{id:6,name:"running",foo:'bar'}]}]
const mapped = data.map(({ interests }) =>
  // Extract only `id` and `foo` properties, excluding the `name`s:
  interests.map(({ id, foo }) => ({ id, foo }))
);
console.log(mapped);

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

Updating the state of Formik

Currently, I'm knee-deep in a React project that requires a slew of calculations. To manage my forms, I've turned to Formik, and for extra utility functions, I've enlisted the help of lodash. Here's a peek at a snippet of my code: impor ...

Is it possible to showcase a dropdown list within a constantly changing table?

I have a table code snippet that I need help with <fieldset class="tabular"><legend><%= l(:redmine_taskjuggler) %></legend> <%= labelled_fields_for(@issue) do |f| %> <div id="taskjuggler" class="attributes"> <div cl ...

Exploring a utility function for saving object information in a dynamic state

Imagine my state was structured like this: state = { customer: { name: { elementType: "input", elementConfig: { type: "text", placeholder: "Your Name" }, value: "" }, street: { e ...

What is the best way to incorporate a mongoose model into another model?

I have two different models that I am working with. In the user model, I want to include an array of Requests, and in the Request Model, I want to have User as an attribute (without including the password). How can I achieve this? var userSchema = new S ...

Passing data from the server to the HTML page for manipulation

I need assistance in retrieving and manipulating the value stored in the variable $result[] from a PHP file to my HTML file for further processing. Can you provide guidance or reference code on how to return data from server side to client side? Here is a ...

Creating a new list by grouping elements from an existing list

I have successfully received data from my API in the following format: [ {grade: "Grade A", id: 1, ifsGrade: "A1XX", ifsType: "01XX", points: 22, type: "Type_1"}, {grade: "Grade B", id: 2, ifsGrade: &quo ...

Arranging a dropdown list of options in alphabetical order using Javascript

Could you assist me in sorting my select list alphabetically? Below is the code I currently have:- $.getJSON("php/countryBorders.geo.json", (data) => { $select.html(""); for (let i = 0; i < data["features"].leng ...

What is the best way to add elements with two attributes to an array in JavaScript?

Imagine trying to create the array structure shown below programmatically using the push() function in JavaScript: var arr = [ {id: 1, txt: "First Element"}, {id: 2, txt: "Second Element"}, {id: 3, txt: "Third Element"} ]; My initial attempt was as follo ...

Deciphering a Base64 document from a JSON reply on the user's end: What's the process?

My project involves rendering a file on the server side, where I pass it as a "base64" string via json. I am now faced with the task of decoding and downloading this file on the client side. Below is a simplified version of the code that is relevant to my ...

Embedding the local host into a href link in NextJS

After creating a menu with the Link component in NextJs using href=#contact, I encountered an issue. When I use querySelector on this a element, the href unexpectedly changes to http://localhost:3000/#contact', preventing me from scrolling to that sec ...

executing ajax request to call a function, encountering partial success and encountering partial failure

Apologies for the lack of clarity in the title. I currently have a search engine that utilizes an ajax function. At present, when I type "t" in the search box, only the tags containing the word "t" are displayed (for example, if I type "t", then "test" sho ...

Issue detected: Click event for Backbone not properly registered

Hey there, I'm new to Backbone.js and having some trouble with a login feature. Despite initiating the view, I can't seem to get the click event to fire during an ajax call for logging in. Any ideas on what I might be doing wrong? I've even ...

The Vue production build displays a blank page despite all assets being successfully loaded

After running npm run build, I noticed that my vue production build was displaying a blank page with the styled background color from my CSS applied. Looking at the page source, I saw that the JS code was loading correctly but the content inside my app d ...

Retrieve the thousand separator for numbers using Angular in various languages

When using the English locale, numbers appear as follows: 111,111,222.00, with a comma as the thousand separator and a point as the decimal separator. In languages like German, the same number would be represented as 111.111.222,00, reversing the positions ...

What is the process for transforming a list of strings into a JSON array using a shell command?

Is there a more efficient way to parse and convert a list of strings into a JSON string array using shell commands? '["test1","test2","test3"]' and output it as: test1 test2 test3 I have attempted the following method: string=$1 array=${string# ...

CSS3 Flexbox creating excess space on the right side

My website currently has a 4 column layout with each div set to a width of 25%, which is resulting in empty space on the right side. How can I adjust this layout to fill the entire screen width? https://i.sstatic.net/d0cJ6.png I have created a flexbo ...

The React component patiently waits for the necessary props before rendering

When declaring a component within another parent component, I prefer to define specific props in one file and then assign additional shared properties in the parent component. However, I am encountering an issue where the child component fails to render be ...

AJAX isn't quite cooperating - it seems that only the error callback is getting

Even though I have specified both success and error callbacks, the error callback is being triggered even when the status code is 200. In addition, I am also making a curl call to another php file within registry.php. This is what I have attempted: $.aj ...

Error: `$(...).fullCalendar is not a function` when using React

After scouring through multiple posts discussing similar issues, I've noticed a common theme of problems arising from improperly loading jQuery or fullcalendar. However, in my case, I have both components loaded into my code (although I can't be ...

AngularJS does not support the 'Access-Control-Allow-Origin' header

I'm struggling to find a solution for the cross-domain issue in my code: $apiUrl = 'https://gtmetrix.com/api/0.1/test'; $apiUser = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c2a8ada755e4b3afb5bcb9acabb ...