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)
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With