I am trying to use reduce
to convert a nested array to an object.
I want to convert var bookprice = [["book1", "$5"], ["book2", "$2"], ["book3", "$7"]];
to
var bookpriceObj = {
"book1": "$5",
"book2": "$2",
"book3": "$7"
};
here is what I tried
var bookprice = [["book1", "$5"], ["book2", "$2"], ["book3", "$7"]];
bookpriceObj = {};
bookprice.reduce(function(a, cv, ci, arr){
for (var i = 0; i < arr.length; ++i)
bookpriceObj [i] = arr[i];
return bookpriceObj ;
})
but the below result is not the desired result
{
["book1", "$5"]
["book2", "$2"]
["book3", "$7"]
}
fromEntries() method was introduced, which converts an array of two-item arrays to an object—effectively the reverse of the . entries() method.
const arr = [ [ ['dog', 'Harry'], ['age', 2] ], [ ['dog', 'Roger'], ['age', 5] ] ]; We are required to write a JavaScript function that takes in one such nested array. The function should then prepare an object based on the array.
A nested data structure is an array or object which refers to other arrays or objects, i.e. its values are arrays or objects. Such structures can be accessed by consecutively applying dot or bracket notation. Here is an example: const data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] };
Nested Array in JavaScript is defined as Array (Outer array) within another array (inner array). An Array can have one or more inner Arrays. These nested array (inner arrays) are under the scope of outer array means we can access these inner array elements based on outer array object name.
Using forEach is shorter
var bookprice = [["book1", "$5"], ["book2", "$2"], ["book3", "$7"]];
var bookpriceObj = {};
bookprice.forEach(e=>bookpriceObj[e[0]] = e[1]);
console.log(bookpriceObj)
You can use reduce with Array Destructoring.
bookpriceObj = bookprice.reduce((a, [b, c]) => (a[b] = c, a), {});
Here's what's happening:
a
is the accumulator which has an initial value of the final parameter passed to reduce
. The last value we pass is {}
so it's an object[a, b] = ["one", "two"]
assigns a
with a value of "one"
and b
with a value of "two"
b
(a.e. "book1") as a property on the object(a
) and give it a value equal to c
(a.e. "$2")reduce
you must return the accumulator(a
)bookpriceObj
the result!var bookprice = [ ["book1", "$5"], ["book2", "$2"], ["book3", "$7"]],
bookpriceObj = bookprice.reduce((a, [b, c]) => (a[b] = c, a), {});
console.log(bookpriceObj)
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