我有一个对象,我试图映射到一个反应组件(使用lodash)。我回来从我的API(火力)的对象的当前形状看起来像这样...用map重构一个对象for each
// 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()
运行我“M试图做的是让我的物体的形状:
// 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.
})
})
}
想法?思考?谢谢。
YAS !!!这正是我所追求的,我希望自己有一个更好的把握这在做什么... – archae0pteryx
@ archae0pteryx请参阅[Object.entri es()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries),[解构赋值](https://developer.mozilla.org/en -US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment),[Spread语法](https://developer.mozilla。org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator), – guest271314
这非常有帮助。谢谢! – archae0pteryx