To convert an array to an object, use the reduce() method to iterate over the array, passing it an object as the initial value. On each iteration, assign a new key-value pair to the accumulated object and return the result. Copied! const arr = ['zero', 'one', 'two']; const obj4 = arr.
Answer: Yes. Java can have an array of objects just like how it can have an array of primitive types.
To create an object from two arrays:Use the reduce() method to iterate over the first array. Provide an empty object as the initial value for the accumulator. Using the index, assign the key-value pair to the accumulated object. Return the result.
To convert an array of objects to a Map , call the map() method on the array and on each iteration return an array containing the key and value. Then pass the array of key-value pairs to the Map() constructor to create the Map object.
Simply
const obj = {};
for (const key of yourArray) {
obj[key] = whatever;
}
or if you prefer "functional" style:
const obj = yourArray.reduce((o, key) => Object.assign(o, {[key]: whatever}), {});
using the modern object spread operator:
const obj = yourArray.reduce((o, key) => ({ ...o, [key]: whatever}), {})
Example:
[
{ id: 10, color: "red" },
{ id: 20, color: "blue" },
{ id: 30, color: "green" }
].reduce((acc, cur) => ({ ...acc, [cur.color]: cur.id }), {})
Output:
{red: 10, blue: 20, green: 30}
Here is how it works:
reduce
is initialized with an empty object (empty {}
at the end), therefore first iteration variables are acc = {}
cur = { id: 10, color: "red" }
. Function returns an object - this is why function body is wrapped in parentheses => ({ ... })
. Spread operator doesn't do anything on the first iteration, so red: 10
is set as first item.
On the second iteration variables are acc = { red: 10 }
cur = { id: 20, color: "blue" }
. Here the spread operator expands acc
and the function returns { red: 10, blue: 20 }
.
Third iteration acc = { red: 10, blue: 20 }
cur = { id: 30, color: "green" }
, so when acc
is spread inside the object, our function returns the final value.
The new Object.fromEntries
, from ECMAScript 2019, makes it even easier to transform values from an array into keys in an object like follows
const dynamicArray = ["2007", "2008", "2009", "2010"];
const obj = Object.fromEntries(
dynamicArray.map(year => [year, {
something: "based",
on: year
}])
)
console.log(obj)
in js with es6 reduce function for array I do it like this
let x = [1,2,3]
let y = x.reduce((acc, elem) => {
acc[elem] = elem // or what ever object you want inside
return acc
}, {})
console.log(y) // {1:1, 2:2, 3:3}
var keys = ['key1', 'key2', 'key3']
var object = Object.assign({}, ...Object.entries({...keys}).map(([a,b]) => ({ [b]: 'someValue' })))
console.log(object)
This will produce
{ key1: 'someValue', key2: 'someValue', key3: 'someValue' }
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