【发布时间】:2017-08-12 23:01:04
【问题描述】:
我有一个对象,我正试图映射到一个反应组件(使用 lodash)。我从 API(firebase)返回的对象的当前形状如下所示......
// 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"
}
}
...但是,当我运行_.map()时,我失去了主键
我想要做的是让我的对象变成以下形状:
// ex. 2
[
{
"id": "-Kdkahgiencls0dnh",
"name": "a name",
"desc": "a description",
"other": "some other guff"
},
{... the next object ...},
{... etc ...}
]
我现在正在做的是在 componentWillMount 生命周期方法中获取我的数据,如下所示:
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.
})
})
}
想法?想法?谢谢。
【问题讨论】:
标签: javascript arrays reactjs object lodash