Home > Net >  Object.entries splitting function strangely?
Object.entries splitting function strangely?

Time:04-05

I have an object like this:

{
 'icon':'info',
 'size':'small',
 'content':'label'
}

I'm trying to split it up into an array of new objects where there is one property per object:

{'icon':'info'}, {'size':'small'} , {content':'label}

I thought I could do this using Object.entries like this:

Object.entries(controlsObject).map(prop => ({ prop }))

But it's really not working out for me - is there another way? Where am I going wrong?

CodePudding user response:

You should instead do this:

Object.entries(controlsObject).map(([key, value]) => ({ [key]: value }))

CodePudding user response:

You can achieve this using Object.entries and reduce:

const t = {
 'icon':'info',
 'size':'small',
 'content':'label'
}

function objToArr(obj){
  return Object.entries(obj).reduce((acc, curr)=>{
    return [...acc, {[curr[0]]:curr[1] }]  
  },[])
}


console.log(objToArr(t)) 

[ { icon: 'info' }, { size: 'small' }, { content: 'label' } ]

CodePudding user response:

You can use computed property names to construct the object:

const obj = {
 'icon':'info',
 'size':'small',
 'content':'label'
}

const res = Object.entries(obj).map(e => ({ [e[0]]: e[1] }))
console.log(res)

CodePudding user response:

Try this:

Object.entries(x).map(([k, v]) => ({ k:v }))

P.S k is key and v is value

  • Related