我如何转换一个大对象数组与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...}]
如果你想要一些对象到数组的自定义映射(比如原始的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
将对象转换为数组与纯JavaScript的(ECMAScript-2016)对象。
Var obj = {
22:{名称:“约翰”,id: 22岁的朋友:[55]5日31日,工作原理:{书:[]、电影:[]}},
12:{名称:“伊万”,id: 12,朋友:[2,44岁,12],工作原理:{书:[]、电影:[]}}
}
var values = Object.values(obj)
console.log(值);
如果你还想保留键,使用Object。entry和array# map像这样:
Var obj = {
22:{名称:“约翰”,id: 22岁的朋友:[55]5日31日,工作原理:{书:[]、电影:[]}},
12:{名称:“伊万”,id: 12,朋友:[2,44岁,12],工作原理:{书:[]、电影:[]}}
}
var values = Object.entries(obj)。Map (([k, v]) => ({[k]: v}))
console.log(值);
对象到数组
在所有的答案中,我认为这个是最好的:
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": []
}
}
]"