Reputation: 51
I have this array of objects:
const array = [{name: 'chips', size: 'medium'}, {name: 'burguer', size: 'large'}].
And I want to convert it to this:
{description: 'chips medium, burguer large'}
How can I do it? I have been trying with reduce without success.
Upvotes: 1
Views: 62
Reputation: 182
This can be implemented only using reduce method (not using maps) as below
const array = [{ name: 'chips', size: 'medium' }, { name: 'burguer', size: 'large' }]
const result = {
description: array.reduce((previousValue, currentValue) =>
Object.values(previousValue).concat(Object.values(currentValue).join(' ')), [],).toString()
}
console.log(result);
I think it is a good idea to go through "Sum of values in an object array" and "Flatten an array of arrays" in the mozilla documentation.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
Upvotes: 0
Reputation: 24638
You can use the Array#reduce
method as follows but, as shown by @Nick using the Array#map
method is more straightforward.
const array = [{name: 'chips', size: 'medium'}, {name: 'burguer', size: 'large'}],
output = array.reduce(
({description:d},{name,size}) =>
({description: (d ? `${d}, ` : "") + `${name} ${size}`}),
{});
console.log( output );
Upvotes: 0
Reputation: 147146
You can achieve your desired result using a nested map
and join
s to first join each of the object values in the array and then the elements of the array into the final output:
const array = [{name: 'chips', size: 'medium'}, {name: 'burguer', size: 'large'}]
const result = { description :
array.map(obj => Object.values(obj).join(' ')).join(', ')
}
console.log(result)
Note it's possible the values in the object may not come out in the expected order (especially if you have modified the object) so it may be safer to refer to the properties directly:
const array = [{name: 'chips', size: 'medium'}, {name: 'burguer', size: 'large'}]
const result = { description :
array.map(({ name, size }) => `${name} ${size}`).join(', ')
}
console.log(result)
Upvotes: 4
Reputation: 8623
const array = [{name: 'chips', size: 'medium'}, {name: 'burguer', size: 'large'}];
const result = array.reduce((sum, cur) => {
if (!sum.description) {
sum.description = `${cur.name} ${cur.size}`;
return sum;
}
sum.description += `, ${cur.name} ${cur.size}`;
return sum;
}, {});
console.log(result);
Upvotes: 1