0

I have let's say this object

const obj = {
  background: {
   backgroundColor:{
    background: '#ffffff'
   },
   backgroundImage:{
    background: 'url(...)'
   }
  },
 header:{
  logo:{
   width: '100%'
  },
  title:{
   color: '#000000'
  }
 }
}

And I need to deconstruct it into something like this:

const deconstructedObj = {
   backgroundColor:{
    background: '#ffffff'
   },
   backgroundImage:{
    background: 'url(...)'
   },
   logo:{
    width: '100%'
  },
   title:{
    color: '#000000'
  }
}

This is just an example, my objects are bigger, but idea is the same, first keys need to be deconstructed, how do I do that?

1
  • Maybe the way to look at it is the first keys need to be removed Commented Jul 13, 2021 at 18:16

2 Answers 2

2

This would get you there, since you only want the values of the outer objects. Object.values will grab those inner objects into an iterable array and array.reduce() will help concatenate them all into a single object result

Object.values(obj).reduce( (b,a) => ({...b, ...a}),{})

const obj = {
  background: {
    backgroundColor: {
      background: '#ffffff'
    },
    backgroundImage: {
      background: 'url(...)'
    }
  },
  header: {
    logo: {
      width: '100%'
    },
    title: {
      color: '#000000'
    }
  }
}
const decon = Object.values(obj).reduce( (b,a) => ({...b, ...a}),{})
console.log(decon)

Sign up to request clarification or add additional context in comments.

Comments

0

If you need only certain keys, or your needed keys are nested at various levels, you can try something like this:

const obj = {
  background: {
   backgroundColor:{
    background: '#ffffff'
   },
   backgroundImage:{
    background: 'url(...)'
   }
  },
 header:{
  logo:{
   width: '100%'
  },
  title:{
   color: '#000000'
  }
 }
}


const { background: { backgroundColor, backgroundImage }, header: { logo, title } } = obj;

const destructuredObj = {
  backgroundColor,
  backgroundImage,
  logo,
  title
}

console.log(destructuredObj)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.