首页 > 解决方案 > 如何将对象对象的对象解构为对象的对象?

问题描述

我让我们说这个对象

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

我需要把它解构成这样:

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

这只是一个例子,我的对象更大,但想法是一样的,第一个键需要解构,我该怎么做?

标签: javascriptobject

解决方案


这将使您到达那里,因为您只需要外部对象的值。Object.values会将这些内部对象抓取到一个可迭代数组中,而array.reduce()将帮助将它们全部连接成一个对象结果

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)


推荐阅读