Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flatten object inside array

I'm trying to apply the value of the first key:value pair to each value inside the array of the second key:value pair while removing the keys from the books array, resulting in a list that takes this input:

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}
    ]
  }
]

and log this output:

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

Where I get stuck

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)
like image 940
Alt-Rock Ninja Cowgirl Avatar asked Dec 28 '16 18:12

Alt-Rock Ninja Cowgirl


People also ask

How do you flatten a nested array of objects?

The “Array. flat()” method is embedded in ES6 that enables you to “flatten” a nested JavaScript Array. This method returns a new array in which all of the elements of sub-arrays are concatenated according to the specified depth.

Can you flatten an array?

Flattening an array is a process of reducing the dimensionality of an array. In other words, it a process of reducing the number of dimensions of an array to a lower number.

How do you merge an array of objects into a single object?

assign() method to convert an array of objects to a single object. This merges each object into a single resultant object. The Object. assign() method also merges the properties of one or more objects into a single object.


1 Answers

You can map the result of books like this

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

console.log(collection);

Output

[ [ [ '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 of the items in the fictionCatalog, we apply a function and gather the results in an array. Now, that function actually applies another function to all of its books and returns an array as a result. The second function (applied to all the books), returns the current author, book name and its price.

like image 107
thefourtheye Avatar answered Oct 09 '22 14:10

thefourtheye