我如何转换一个大对象数组与lodash?
var obj = {
22: {name:"John", id:22, friends:[5,31,55], works:{books:[], films:[],}
12: {name:"Ivan", id:12, friends:[2,44,12], works:{books:[], films:[],}
}
// transform to
var arr = [{name:"John", id:22...},{name:"Ivan", id:12...}]
对象到数组
在所有的答案中,我认为这个是最好的:
let arr = Object.entries(obj).map(([key, val]) => ({ key, ...val }))
转换:
{
a: { p: 1, q: 2},
b: { p: 3, q: 4}
}
to:
[
{ key: 'a', p: 1, q: 2 },
{ key: 'b', p: 3, q: 4 }
]
数组到对象
变回来:
let obj = arr.reduce((obj, { key, ...val }) => { obj[key] = { ...val }; return obj; }, {})
将键保留在值中进行反向转换:
let obj = arr.reduce((obj, { key, ...val }) => { obj[key] = { key, ...val }; return obj; }, {})
将:
{
a: { key: 'a', p: 1, q: 2 },
b: { key: 'b', p: 3, q: 4 }
}
对于最后一个例子,你也可以使用lodash _。keyBy(arr, 'key')或_。keyBy(arr, i => i.key)。
对象到数组
在所有的答案中,我认为这个是最好的:
let arr = Object.entries(obj).map(([key, val]) => ({ key, ...val }))
转换:
{
a: { p: 1, q: 2},
b: { p: 3, q: 4}
}
to:
[
{ key: 'a', p: 1, q: 2 },
{ key: 'b', p: 3, q: 4 }
]
数组到对象
变回来:
let obj = arr.reduce((obj, { key, ...val }) => { obj[key] = { ...val }; return obj; }, {})
将键保留在值中进行反向转换:
let obj = arr.reduce((obj, { key, ...val }) => { obj[key] = { key, ...val }; return obj; }, {})
将:
{
a: { key: 'a', p: 1, q: 2 },
b: { key: 'b', p: 3, q: 4 }
}
对于最后一个例子,你也可以使用lodash _。keyBy(arr, 'key')或_。keyBy(arr, i => i.key)。
_.toArray(obj);
输出为:
[
{
"name": "Ivan",
"id": 12,
"friends": [
2,
44,
12
],
"works": {
"books": [],
"films": []
}
},
{
"name": "John",
"id": 22,
"friends": [
5,
31,
55
],
"works": {
"books": [],
"films": []
}
}
]"
如果你想要一些对象到数组的自定义映射(比如原始的Array.prototype.map),你可以使用_.forEach:
let myObject = {
key1: "value1",
key2: "value2",
// ...
};
let myNewArray = [];
_.forEach(myObject, (value, key) => {
myNewArray.push({
someNewKey: key,
someNewValue: value.toUpperCase() // just an example of new value based on original value
});
});
// myNewArray => [{ someNewKey: key1, someNewValue: 'VALUE1' }, ... ];
参见lodash doc of _。forEach https://lodash.com/docs/ # forEach