Reputation: 97
I have an array of several objects
array1 =[ {1:Eat},{2:Shower},{3:Shave}]
I want to convert this array into a single object
object1 ={1:Eat, 2:Shower, 3:Shave}
How do I go about it. The keys(1,2,3) are unique
Upvotes: 1
Views: 39
Reputation: 380
THE SOLUTION
array.reduce((a, v) => Object.assign(a,v), {})
THE EXPLANATION
Array.reduce() loops throw the initial array aimed to "reduce" it into a single object. The reduce method allows you to store the return value of each of your iterations. It requires an initial value which in this case it will be the empty object {} that we will be filling up with our array.
Then we use Object.assign(target, source) which concatenates two objects together returning the concatenated object which in this case it will saved into our accumulator and be used as a target for the next iteration giving you when it finishes the constructed final object. As you have objects as the keys of the array, each single property Object(source) will be "assigned" to a master one (target) that will be collecting all of them into one.
array1 =[ {1:'Eat'},{2:'Shower'},{3:'Shave'}]
obj1 = array1.reduce((a, v) => Object.assign(a,v), {})
console.log(obj1)
Upvotes: 1
Reputation: 2869
I'm not sure if my method of using Object.keys()
and Object.values()
is the most efficient method, but it's something to get you started:
array1 = [{
1: "Eat"
}, {
2: "Shower"
}, {
3: "Shave"
}];
object1 = {};
array1.forEach(v => {
object1[Object.keys(v)[0]] = Object.values(v)[0];
});
console.log(object1);
Upvotes: 0
Reputation: 66
You could simply loop through the array and each object within it and add it to a master object as shown below.
const array1 =[{ 1: 'Eat' }, { 2: 'Shower' }, { 3: 'Shave' }];
const masterObj = {};
array1.forEach(obj => {
for (const property in obj) {
masterObj[property] = obj[property];
};
});
console.log(masterObj);
Upvotes: 0
Reputation: 178421
fromEntries and a flatMap seems to do the trick nicely
const array1 = [ {1:'Eat'},{2:'Shower'},{3:'Shave'}]
const obj1 = Object.fromEntries(array1.flatMap(item => Object.entries(item)))
console.log(obj1)
Upvotes: 0
Reputation: 48751
The easiest way to achieve this is to reduce the list of objects into a single object.
const
input = [{ 1: 'Eat' }, { 2: 'Shower' }, { 3: 'Shave' }],
output = input.reduce((acc, obj) => ({ ...acc, ...obj }), {});
console.log(output);
.as-console-wrapper { top: 0; max-height: 100% !important; }
Upvotes: 1