Home > Software engineering >  reduce method JavaScript, convert 2 objects in a single one
reduce method JavaScript, convert 2 objects in a single one

Time:09-08

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.

CodePudding user response:

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)

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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(' ')), [],)
}

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