Flatten an object that is nested inside an array

I want to take the value of the first key:value pair and apply it to each value in the array of the second key:value pair, all while removing the keys from the books array. This process will result in a list that looks like this:

var fictionCatalog = [
  {
    author: 'Michael Crichton',// push into each book
    books: [
      {name: 'Sphere', price: 10.99},
      {name: 'Jurassic Park', price: 5.99},
      {name: 'The Andromeda Strain', price: 9.99},
      {name: 'Prey', price: 5.99}
    ]
  }
]

The desired output should be:

[
 [ Michael Crichton, 'Sphere', 10.99 ], 
 [ Michael Crichton, 'Jurassic Park', 5.99 ],
 [ Michael Crichton, 'The Andromeda Strain', 9.99 ],
 [ Michael Crichton, 'Prey', 5.99 ]
]

However, I am facing difficulties with the following code snippet:

var fictionCatalog = [
  {
    author: 'Michael Crichton',
    books: [
      {name: 'Sphere', price: 10.99},
      {name: 'Jurassic Park', price: 5.99},
      {name: 'The Andromeda Strain', price: 9.99},
      {name: 'Prey', price: 5.99}
    ]
  }
]

var collection = fictionCatalog.reduce(function(prev, curr) {
  return prev.concat(curr.author, curr.books);
}, []);

console.log(collection)

Answer №1

To transform the data from the books array, you can use a mapping function like so:

var collection = fictionCatalog.map(function(obj) {
  return obj.books.map(function(book) {
    return [obj.author, book.name, book.price];
  });
});

console.log(collection);

Result:

[ [ [ 'Michael Crichton', 'Sphere', 10.99 ],
    [ 'Michael Crichton', 'Jurassic Park', 5.99 ],
    [ 'Michael Crichton', 'The Andromeda Strain', 9.99 ],
    [ 'Michael Crichton', 'Prey', 5.99 ] ] ]

For each entry in the fictionCatalog, we apply a mapping function and gather the output in an array. This function then further applies another function to each book within the entry, returning an array containing the author's name, book title, and price.

Answer №2

Using a combination of map functions can help solve the problem

var fictionCatalog = [
  {
    author: 'Michael Crichton',// push into each book
    books: [
      {name: 'Sphere', price: 10.99},
      {name: 'Jurassic Park', price: 5.99},
      {name: 'The Andromeda Strain', price: 9.99},
      {name: 'Prey', price: 5.99}
    ]
  }
];

var res = fictionCatalog.map(v => {
  return v.books.map(k => {
  return [v.author, k.name, k.price];
  })
});

console.log(res);

Answer №3

If I were to solve this, I would use a simple loop:

var fictionCatalog = [
  {
    author: 'Michael Crichton',
    books: [
      {name: 'Sphere', price: 10.99},
      {name: 'Jurassic Park', price: 5.99},
      {name: 'The Andromeda Strain', price: 9.99},
      {name: 'Prey', price: 5.99}
    ]
  }
]

var collection = [];

for (var a = 0; a < fictionCatalog.length; a++) {
  var author = fictionCatalog[a].author;
  for (var b = 0; b < fictionCatalog[a].books.length; b++) {
     collection.push([
         author,
         fictionCatalog[a].books[b].name,
         fictionCatalog[a].books[b].price
     ]);
  }
}

console.log(collection)

Answer №4

What do you think of this approach:

let fictionAuthors = [
 {
   name: 'Michael Crichton',
   novels: [
      {title: 'Sphere', cost: 10.99},
      {title: 'Jurassic Park', cost: 5.99},
      {title: 'The Andromeda Strain', cost: 9.99},
      {title: 'Prey', cost: 5.99}
    ]
  }
]

let bookList = fictionAuthors.reduce(
  function(previous, current) {  
    return previous.concat( current.novels.map( 
                               function(item) { 
                                 return [ current.name, item.title, item.cost ]; 
                               }));
}, []);

This method utilizes the reduce and map functions to create the desired array structure.

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

You cannot cast java.lang.Double to abie47_0_0.com.facebook.react.bridge.ReadableMap in this scenario

While using react-native-gifted-charts, I encountered the error message "java.lang.Double cannot be cast to abie47_0_0.com.facebook.react.bridge.ReadableMap" when opening the app on my Android device. This error occurred after implementing react ...

Patience is key when using Selenium with Node.js - make sure to wait for the

Is there a way to ensure my code waits until the page is fully loaded in Node.js while using selenium-webdriver version 4.0.0? const driver = new Builder().forBrowser("firefox").build(); await driver.get("http://www.tsetmc.com/Loader.a ...

Using jQuery to enhance the functionality of the drop-down select feature

I am facing an issue with my index file code. When I select something from the drop-down menu, I expect to see a related dropdown appear. Although I have added this code to my file, I am unable to get the drop down to show after selecting the main type. ...

Set up global variables for components to access

Currently, I am working on a Laravel 8 project with vue-sweetalert2 integration. My goal is to set up the Toast behavior once and then be able to call it within various components. At the moment, my code looks like this: /js/components/Mypage.vue <scr ...

What is the best way to modify navbar-default to navbar-inverse when scrolling?

On the header of my webpage, the primary navigation class is called: navbar navbar-default navbar-fixed-top bg I am attempting to create a smoother scroll animation by changing the class when scrolling as follows: navbar navbar-inverse navbar-fixed-top ...

What is the best way to highlight the option with a value of 0 by giving it a red background using either CSS, jQuery, or both, regardless of whether it is

I have tried various CSS and jQuery combinations to address the issue of displaying the option with a value of 0 in red only when it is not selected. .red { background: red; } select option[value=0] { background: red; } <select id="ups"> < ...

Issues encountered with Jquery hover functionality not responding as expected

When the mouse hovers over it, I want to explain changing the src of img tag as much as possible; here is the HTML: <ul id="nav-tabs" data-tabs="tabs"> <li id="test" style="list-style: none;" class="active"> <a href="#home" data-toggle ...

Error: the function was not defined and has not been caught

In an effort to develop a quiz application, I am working on a feature that will increment a counter when the correct answer is selected. While I have identified the correct answer, I am struggling with implementing a method called correctTest to achieve th ...

Generating random strings does not modify my string array in C++

Every time my randomizing function runs, it produces empty strings. I've tried manually inputting values and that works fine. I attempted to use pointers as well but kept getting error messages. void random(string Arr[], int ArrSize){ for(int i ...

Implementing re-render logic for a React functional component based on changes in useState()

I've created a basic functional component that retrieves a date from localStorage and displays it. The component includes two buttons to add or remove weeks from the date, expecting the updated date to be shown. However, I'm facing an issue where ...

Why is the ExpressJS response for a POST request returning as undefined upon connecting to MongoDB?

I am currently working on a web application using the MEAN framework and following the MVC design pattern. My goal is to execute a POST request from the Angular front-end to search for a document in my server-side MongoDB (version 2.4.9). The console logs ...

Error alert: Unable to find the specified word

Having trouble writing a word to the database due to an error: ReferenceError: Patikrinta is not defined. Below is my ajax script for sending data to a PHP file, and then the PHP script itself if needed. Haven't found a solution on Stack Overflow. $s ...

Troubles with NextJS and TailwindCSS Styling

I encountered a strange issue when I used the component separately. Here's how the code looked like: <> <Head> <title>Staycation | Home</title> <meta name="viewport" content="initial- ...

Filter Observable based on object array property

I am trying to filter an Observable and only keep the stream that has a specific property value in an array of objects inside it. For example, consider this Observable: const observable = of({name: 'agency', year: '2010', job: [ ...

Create a 3D visual display with the use of three.js in Javascript

I'm navigating my second round with three.js and have been experimenting for a good 3 hours. However, I seem to be at a loss when it comes to determining my next steps. My goal is to create something similar to the layout found here: I've manag ...

Netlify encountered an error with mixed content, indicating that the page was successfully loaded over HTTPS, but it attempted to request an insecure HTTP

hey everyone, Recently, I deployed my vue-cli website project on Netlify. However, upon opening the website, I encountered the following error message: Mixed Content: The page at 'https://xxxx.netlify.app/' was loaded over HTTPS, but requested a ...

Issue with Ajax: parameters failing to pass without using jQuery

It appears that I am only receiving jQuery results, but I am in search of the correct method to pass parameters via AJAX without using libraries or old browser fallbacks. If there is another thread discussing this topic that I have overlooked, please provi ...

"Add a hover effect to fade the image and make it clickable for a

Is there a way to make the entire image a clickable link when it's hovered over, rather than just the text inside? I could use some assistance with this. Javascript: $('.thumbnail').hover(function() { $('.thumbnail img').stop ...

Creating a struct in C that contains a multidimensional, dynamic array where the size is determined by an integer defined within the same struct

I am currently working on a game where the levels are based on a 2D array, but I need the size of the array to be variable for each level. After doing some research, I came across this question that had a similar issue to mine. I tried implementing the sol ...

Connect the mileage tracker to a Datalist or grid view component

I recently downloaded the Odometer Sample from , however, I am facing an issue where only the first element in the Datalist is getting the Odometer display, while others are not displaying it. Here is the snippet of code: <script type="text/javascript" ...