Search code examples
javascriptarraysjsonjavascript-objects

Convert array into specific object


Given the following JSON

{
gif: ['small', 'medium', 'large'],
jpeg: ['tiny', 'huge']
}

I would like to convert each element in the array into a key in a sub object and assign it to it a quantity of 1.

As such

{
gif: {
  small: {quantity: 1},
  medium: {quantity: 1},
  large: {quantity:1}
  },
jpeg: {
  tiny: {quantity:1},
  huge: {quantity: 1}
  }
}

The closest I've come is with the following

for(let image in obj) { 
  obj[image].forEach(size => { obj[image][size] = { quantity:1}})
}

However unfortunately this out puts

{ gif: 
  [ 'small',
    'medium',
    'large',
     small: {quantity: 1},
     medium: {quantity: 1},
     large: {quantity: 1} ],
 jpeg: [ 'huge', 'tiny', tiny: {quantity:1} huge: {quantity: 1 } ] 
} 

Any help would be awesome, thanks


Solution

  • You can use the .reduce() method

    const obj = {
      gif: ['small', 'medium', 'large'],
      jpeg: ['tiny', 'huge']
    };
    
    
    for (let image in obj) {
      obj[image] = obj[image].reduce((result, item) => {
        result[item] = {
          quantity: 1
        };
        return result;
      }, {});
    }
    
    console.log(obj);