reduce method JavaScript, convert 2 objects in a single one

Viewed 47

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.

4 Answers

You can achieve your desired result using a nested map and joins 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)

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);

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 );

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

Related