Retrieving a specific value from a collection of nested arrays containing objects

Having trouble extracting values from fields and have tried various methods like nesting the map function and concatenating fields without success.

I have an object with a structure similar to this:

[{ 
   name: 'sean', 
   age: 26, 
   address: 
      [{ 
         street: 'red'
       }, 
       { 
         street: 'blue'
       }]
}];

My goal is to extract the street value from this structure and store it in a new array. The desired result would be:

 const newArray = ['red', 'blue'];

The address field may contain multiple objects, so the solution should be scalable for handling one or many objects.

Answer №1

const data = [
  {
    name: 'John',
    age: 30,
    address: [
      {street: 'Main St'},
      {street: 'Oak Ave'}
    ]
  },
  {
    name: 'Jane',
    age: 25,
    address: [
      {street: 'Maple Rd'},
      {street: 'Pine Lane'}
    ]
  }
];

const newStreetArray = input.flatMap(({address}) => address.map(({street}) => street));
console.log(newStreetArray);

Array.prototype.flatMap is a method that takes a callback function and returns a single array composed of the elements inside the arrays returned by the callback. Essentially, using array.flatMap(callback) achieves the same result as array.map(callback).flat().

In your comment, you mentioned attempting to use reduce and concat. However, based on MDN documentation:

var arr = [1, 2, 3, 4];

arr.flatMap(x => [x, x * 2]);
// is equivalent to
arr.reduce((acc, x) => acc.concat([x, x * 2]), []);
// [1, 2, 2, 4, 3, 6, 4, 8]

It's important to note this approach can be inefficient with large arrays because it creates temporary arrays in each iteration which must then be garbage-collected. Instead of simply adding new elements, it copies elements from the current accumulator array into a new one.

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

Having trouble verifying the selection option in Angular 6

I've been trying to implement Select option validation in Angular 6, but neither Aria-required nor required seem to be effective. The requirement is for it to display a message or show a RED border similar to HTML forms. Here's the HTML snippet ...

Veracode Scan finds vulnerability in jQuery html method with Improper Neutralization of Script-Related HTML Tags in a Web Page error

Veracode has flagged the issue Improper Neutralization of Script-Related HTML Tags in a Web Page (Basic XSS) within the following line of code. $('#SummaryDiv').html(data); $.ajax({ url: 'Target_URL', type: &a ...

Is it possible to adjust the opacity when the image attribute is altered?

I am trying to achieve a smooth transition when changing the image source on click using previous/next buttons. I want the image to fade out, then change source and fade back in, but I'm having trouble getting it to work seamlessly. I attempted to use ...

The object literal can only define existing properties, and the property 'allAwsRegions' is not found in the 'IResolvable' type

Currently, I am working with the AWS-CDK and attempting to set up a Config Aggregator to combine the storage of configuration logs from all regions. Instead of using an account as the source, I have opted for a region due to restrictions on configuring org ...

Error Occurred: With Twitter Bootstrap wizard, the container has been found to

When using the twitter bootstrap wizard, I am encountering a 'TypeError: container is undefined' error in the console after clicking the 'next' chevron. Despite the error, the wizard continues to display the next tab. What could be caus ...

Having trouble with clearInterval in my Angular code

After all files have finished running, the array this.currentlyRunning is emptied and its length becomes zero. if(numberOfFiles === 0) { clearInterval(this.repeat); } I conducted a test using console.log and found that even though ...

Is it possible to utilize a variable as a column name in MySQL when working with Express?

At the moment, I am encountering an issue where the table name is surrounded by quotation marks as it is a string. This causes the server to crash. const update = 'the name of my column'; const UpdateQuery = `UPDATE scores SET ${mysql.escap ...

Encountering a connection refusal error message while executing Selenium-webdriver

I am attempting to view the raw HTML content before it is displayed by the browser. To achieve this, I am utilizing selenium-webdriver in a node.js environment. Below is my code snippet along with the error message I encountered: Code var webdriver = requ ...

Leveraging the spread operator for setting state in a series of consecutive updates

Within my component, I am retrieving values from local storage and attempting to load them into the state when the component mounts. However, only the last property that I add seems to be included in the state. I have confirmed that all values are present ...

An error occurred while processing the JSReport request

I am encountering an issue while trying to utilize the jsreport API for rendering a report template. The error I am facing is as follows: { body: "{"body":"\"{\\\"template\\\":{\\\"shortid\\& ...

How do I automatically redirect to a different URL after verifying that the user has entered certain words using Javascript?

I want to create a function where if a user input on the "comments" id matches any word in my FilterWord's array, they will be redirected to one URL. If the input does not match, they will be redirected to another URL. The checking process should onl ...

Unraveling the mystery of nested optional indexes in interfaces

Discover the interface outlined on this TS playground export type GetTestimonialsSectionQuery = { __typename?: 'Query', testimonialsSection?: { __typename?: 'TestimonialsSection', id: string, testimonials: Array< ...

The call stack limit has been exceeded due to the combination of Node, Express, Angular, and Angular-route

Embarking on a new SPA journey, my tech stack includes: Back-end: NodeJS + Express Front-end: Angular + Angular-route. Twitter Bootstrap Underscore Having followed many tutorials with similar stacks, my project files are structured as follows: pac ...

Using Regular Expressions in JavaScript for Filtering with Angular.js

I am looking to create a custom filter in Angular.js. When an object has a name == null, and I add "u" to the filter->, it results in the return of the object where name == null because re.test(null)=true. However, other characters are returning false. ...

Using axios to pass parameters in a URL with the GET method on a localhost server

I need help using Axios to consume my Go lang API in my React front-end. The route for the API is localhost:1323/profile/email/:email/password/:password, but I'm struggling to figure out how to pass the email and password parameters in the Axios GET r ...

Obtaining the category value within a slot of the Vuetify calendar

I am struggling to implement hover functionality in the categories view of Vuetify calendar within the body section (slot day-body). When I try to add hover functionality, the entire row ends up being affected by the hover effect, even though I only want i ...

Exploring JSON data for auto-complete suggestions

Upon receiving the object from the source, it looks like this - ["road",[["road",53,"0E"],["roadtrip",53,"1E"],["roadrunner",53,"2E"],["roadster",53,"3E"],["roadside",53,"4E"],["roadrage",53,"5E"],["roadcycling",53,"6E"],["roadsideamerica",53,"7E"]],{"k": ...

Optimizing the import and export process for methods in Node.js

Currently, I am facing challenges when trying to import a method from one class to another in order to maintain organization. However, I keep encountering new errors whenever I attempt different approaches. The primary issue seems to lie with the difficult ...

How to Retrieve Values from a Movie API?

Struggling with The Movie Database API integration. Specifically, I'm stuck on retrieving the "keys" variable when calling the function with the Movie's id. I'm still learning JavaScript, so this is proving to be a bit challenging. Any assis ...

A solitary outcome yielded by the JSON iteration

Can anyone help me understand why this code is only returning 1 result instead of 4? I am trying to retrieve all the post titles in the category with ID 121, but it seems to only display the most recent post title. <script type="text/javascript> ...