Reputation: 11
I have an array of objects which looks like this:
const arr = [
{integer: "3"},
{integer: "500"}
]
As a result i want to get the object that looks like this: mergedObj = {digits: "3500"}
I tried to use reduce, but it seems that i'm doing something wrong. Here is my code:
var mergedObj = arr.reduce((acc, obj) => {
acc["digits"] = [acc[obj.integer]].concat(obj.integer).join("");
return acc;
}, {});
Here is the result of what i'm getting:
"Object is", [object Object] {
digits: "500"
}
The problem is that i'm missing the first part of my digit. Please help me! Thank you in advance!
Upvotes: 0
Views: 44
Reputation: 8515
You almost got this. The [acc[obj.integer]]
part should be [acc.digits]
. Anyway, you can do it much simpler:
const arr = [
{integer: "3"},
{integer: "500"}
]
var mergedObj = arr.reduce((acc, obj) => {
acc.digits += obj.integer;
return acc;
}, { digits: '' });
console.log(mergedObj);
Upvotes: 1
Reputation: 191966
Use Array.map()
to create an array of integer
, and then join. Assign to digits
property of a new object:
const arr = [
{integer: "3"},
{integer: "500"}
]
const result = {
digits: arr.map(o => o.integer).join('')
};
console.log(result);
Upvotes: 2
Reputation: 1767
Try this below :
const arr = [
{integer: "3"},
{integer: "500"}
]
let output = {'digits':''};
arr.map(function (item) {
output['digits'] += item['integer']
});
console.log(output);
Upvotes: 0