Skip to content
Advertisement

How to invert a nested object of objects

I’d like to learn how to convert a nested object into a new one by rearranging this structure:

data = 
  { 
    centeredSlides: { 
      0: true, 
      1300: false 
    }, 
    somethingElse: { 
      0: false, 
      1500: 'aString' 
    } 
  }

So that it follows this structure:

newData = 
  {
    0: {
      centeredSlides: true,
      somethingElse: false
    },
    1300: {
      centeredSlides: false
    },
    1500: {
      somethingElse: 'aString'
    }
  }

Thanks

Advertisement

Answer

You can grab the entires of your object and use .reduce() to build a new object from the [[key, value], ...] entry array. For each [key, value] you can iterate over the entries of the nested object and use the keys from that as your outer keys of your accumulated/new object:

const data = { centeredSlides: { 0: true, 1300: false }, somethingElse: { 0: false, 1500: 'aString' } };

const res = Object.entries(data).reduce((acc, [innerKey, obj]) => {
  Object.entries(obj).forEach(([outerKey, val]) => {
    acc[outerKey] = acc[outerKey] || {}; // grab the object already stored at the `outerKey` or create a new one.
    acc[outerKey][innerKey] = val;
  })
  return acc;
}, {});

console.log(res);
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement