我如何转换一个大对象数组与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...}]

当前回答

对我来说,这很有效:

_.map(_.toPairs(data), d => _.fromPairs([d]));

结果

{"a":"b", "c":"d", "e":"f"} 

into

[{"a":"b"}, {"c":"d"}, {"e":"f"}]

其他回答

对象到数组

在所有的答案中,我认为这个是最好的:

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

你可以这样做

var arr = _.values(obj);

有关文档请参见这里。

_.toArray(obj);

输出为:

[
  {
    "name": "Ivan",
    "id": 12,
    "friends": [
      2,
      44,
      12
    ],
    "works": {
      "books": [],
      "films": []
    }
  },
  {
    "name": "John",
    "id": 22,
    "friends": [
      5,
      31,
      55
    ],
    "works": {
      "books": [],
      "films": []
    }
  }
]"

对我来说,这很有效:

_.map(_.toPairs(data), d => _.fromPairs([d]));

结果

{"a":"b", "c":"d", "e":"f"} 

into

[{"a":"b"}, {"c":"d"}, {"e":"f"}]

2017年更新:对象。valuevalues, lodash values和toArray。为了保存键映射和展开操作符,请注意:

//从'lodash'导入{toArray, map} Const map = _.map Const input = { 关键:{ 价值:“价值” } } Const输出= map(input, (value, key) => ({ 键, 价值…… })) console.log(输出) // >> [{key: 'key', value: 'value'}]) < script src = " https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js " > < /脚本>