使用 map 和 forEach 重组对象



>我有一个对象,我正在尝试将其映射到反应组件(使用 lodash(。我从 API(火库(返回的对象的当前形状如下所示......

// 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.
})
})
}

想法?思潮?谢谢。

您可以使用Object.entries().map()和对象展开

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);

Lodash 的_.map()回调作为第二个参数接收迭代键。使用对象分配创建一个以键作为 id 的新对象:

const array = _.map(data, (item, id) => Object.assign({ id }, item))

演示:

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"}};
const array = _.map(data, (item, id) => Object.assign({ id }, item));
console.log(array);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

在这里,只使用纯JS:

const raw = {
"-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 formatted = Object.keys(raw).map(
key=>Object.assign(raw[key], {"id": ""+key})
);

这是获得现场演示的小提琴。

componentWillMount() {
firebaseRef.on('value', snap => {
let data = snap.val() // the whole original object (see ex. 1)
let tempArray = Object.keys(data).map((item, key) => {
return {
"id": item,
"name": data[item].name // etc, a structure what you want
...
};
})
})
}

最新更新