archae0pteryx archae0pteryx - 4 months ago 39
Javascript Question

Restructuring an object with map and forEach

I've got an object that i'm trying to map to a react component (using lodash). The current shape of the objects that I get back from my API (firebase) looks like this...

// ex. 1
{
"-Kdkahgiencls0dnh": {
"name": "a name",
"desc": "a description",
"other": "some other guff"
},
"-Ksdfadfvcls0dsnh": {
"name": "another name",
"desc": "another description",
"other": "some more"
},
"-kgoandiencls0dnh": {
"name": "I am a name",
"desc": "I am a description",
"other": "I am some other guff"
}
}


...but, I loose the primary key when i run through
_.map()


What i'm trying to do is get my object in the shape of:

// ex. 2
[
{
"id": "-Kdkahgiencls0dnh",
"name": "a name",
"desc": "a description",
"other": "some other guff"
},
{... the next object ...},
{... etc ...}
]


What i'm doing now is getting my data in the
componentWillMount
lifecycle method like so:

componentWillMount() {
firebaseRef.on('value', snap => {
let data = snap.val() // the whole original object (see ex. 1)
let tempArray = [] // an array to store my newly formatted objects
_.forEach(data, (item, key) => {
// Here's where i'm not really sure what to do.
// I want to use Object.assign to set a new key:value
// That adds "id": "-theobjectsmainkey" to a new object
// then push to my tempArray and finally setState with the
// correctly formatted array of objects.
})
})
}


Ideas? Thoughts? Thanks.

Answer Source

You can use Object.entries(), .map() and object spread

const data = {
  "-Kdkahgiencls0dnh": {
    "name": "a name",
    "desc": "a description",
    "other": "some other guff"
  },
  "-Ksdfadfvcls0dsnh": {
    "name": "another name",
    "desc": "another description",
    "other": "some more"
  },
  "-kgoandiencls0dnh": {
    "name": "I am a name",
    "desc": "I am a description",
    "other": "I am some other guff"
  }
}

let res = Object.entries(data).map(([id, prop]) => ({id, ...prop}));

console.log(res);