[英]transform object to array with lodash
如何使用 lodash 将大object
转换为array
?
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...}]
如果有人感兴趣,可以使用现代本地解决方案:
const arr = Object.keys(obj).map(key => ({ key, value: obj[key] }));
或(不是 IE):
const arr = Object.entries(obj).map(([key, value]) => ({ key, value }));
_.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"}
进入
[{"a":"b"}, {"c":"d"}, {"e":"f"}]
有很多方法可以得到你想要的结果。 让我们把它们分成几类:
仅 ES6 值:
主要方法是Object.values 。 但是使用Object.keys和Array.map你也可以得到预期的结果:
Object.values(obj)
Object.keys(obj).map(k => obj[k])
var obj = { A: { name: "John" }, B: { name: "Ivan" } } console.log('Object.values:', Object.values(obj)) console.log('Object.keys:', Object.keys(obj).map(k => obj[k]))
ES6 键和值:
使用地图和 ES6 动态/计算属性和解构,您可以保留键并从地图返回一个对象。
Object.keys(obj).map(k => ({[k]: obj[k]}))
Object.entries(obj).map(([k,v]) => ({[k]:v}))
var obj = { A: { name: "John" }, B: { name: "Ivan" } } console.log('Object.keys:', Object.keys(obj).map(k => ({ [k]: obj[k] }))) console.log('Object.entries:', Object.entries(obj).map(([k, v]) => ({ [k]: v })))
仅 Lodash 值:
为此设计的方法是_.values
但是有像_.map
和实用方法_.toArray
这样的“快捷方式”,它也将返回一个只包含来自对象的值的数组。 您也可以通过_.map
_.keys
并使用obj[key]
符号从对象中获取值。
注意: _.map
传递对象时将使用其baseMap
处理程序,该处理程序基本上是对象属性上的forEach
。
_.values(obj)
_.map(obj)
_.toArray(obj)
_.map(_.keys(obj), k => obj[k])
var obj = { A: { name: "John" }, B: { name: "Ivan" } } console.log('values:', _.values(obj)) console.log('map:', _.map(obj)) console.log('toArray:', _.toArray(obj)) console.log('keys:', _.map(_.keys(obj), k => obj[k]))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
Lodash 键和值:
// Outputs an array with [[KEY, VALUE]]
_.entries(obj)
_.toPairs(obj)
// Outputs array with objects containing the keys and values
_.map(_.entries(obj), ([k,v]) => ({[k]:v}))
_.map(_.keys(obj), k => ({[k]: obj[k]}))
_.transform(obj, (r,c,k) => r.push({[k]:c}), [])
_.reduce(obj, (r,c,k) => (r.push({[k]:c}), r), [])
var obj = { A: { name: "John" }, B: { name: "Ivan" } } // Outputs an array with [KEY, VALUE] console.log('entries:', _.entries(obj)) console.log('toPairs:', _.toPairs(obj)) // Outputs array with objects containing the keys and values console.log('entries:', _.map(_.entries(obj), ([k, v]) => ({ [k]: v }))) console.log('keys:', _.map(_.keys(obj), k => ({ [k]: obj[k] }))) console.log('transform:', _.transform(obj, (r, c, k) => r.push({ [k]: c }), [])) console.log('reduce:', _.reduce(obj, (r, c, k) => (r.push({ [k]: c }), r), []))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
请注意,在上面的示例中使用了 ES6(箭头函数和动态属性)。 如果 ES6 有问题,您可以使用 lodash _.fromPairs
和其他方法来组合对象。
如果您希望将键(在这种情况下为 id)作为每个数组项的属性保留,您可以这样做
const arr = _(obj) //wrap object so that you can chain lodash methods
.mapValues((value, id)=>_.merge({}, value, {id})) //attach id to object
.values() //get the values of the result
.value() //unwrap array of objects
2017 年更新: Object.values 、 lodash values和toArray做到了。 并保留键映射和扩展运算符玩得很好:
// import { toArray, map } from 'lodash' const map = _.map const input = { key: { value: 'value' } } const output = map(input, (value, key) => ({ key, ...value })) console.log(output) // >> [{key: 'key', value: 'value'}])
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
使用纯 JavaScript ( ECMAScript-2016
) Object.values
将对象转换为数组:
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:[]}} } var values = Object.values(obj) console.log(values);
如果您还想保留键使用Object.entries
和Array#map
像这样:
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:[]}} } var values = Object.entries(obj).map(([k, v]) => ({[k]: v})) console.log(values);
在所有答案中,我认为这个是最好的:
let arr = Object.entries(obj).map(([key, val]) => ({ key, ...val }))
转换:
{
a: { p: 1, q: 2},
b: { p: 3, q: 4}
}
到:
[
{ 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 = _.map(obj)
您也可以将_.map
函数( lodash
和underscore
)与object
一起使用,它会在内部处理这种情况,用您的 iteratee 迭代每个值和键,最后返回一个数组。 事实上,如果你只想要一个值数组,你可以在没有任何迭代的情况下使用它(只是_.map(obj)
)。 好的部分是,如果您需要在两者之间进行任何转换,您可以一次性完成。
例子:
var obj = { key1: {id: 1, name: 'A'}, key2: {id: 2, name: 'B'}, key3: {id: 3, name: 'C'} }; var array1 = _.map(obj, v=>v); console.log('Array 1: ', array1); /*Actually you don't need the callback v=>v if you are not transforming anything in between, v=>v is default*/ //SO simply you can use var array2 = _.map(obj); console.log('Array 2: ', array2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
但是,如果你想转换你的对象,你可以这样做,即使你需要保留密钥,你也可以这样做( _.map(obj, (v, k) => {...}
)和额外的参数在map
,然后以您想要的方式使用它。
但是,还有其他 Vanilla JS 解决方案(因为每个lodash
解决方案都应该是它的纯 JS 版本),例如:
Object.keys
然后map
它们map
到值Object.values
(在 ES-2017 中)Object.entries
然后map
每个键/值对(在 ES-2017 中)for...in
循环并使用每个键来获取值还有很多。 但是由于这个问题是针对lodash
(并假设有人已经在使用它),那么您无需lodash
考虑版本、方法支持和错误处理(如果没有找到的话)。
还有其他 lodash 解决方案,如_.values
(对于特定的 perpose 更具可读性),或者获取对然后映射等等。 但是如果您的代码需要灵活性,您可以在将来更新它,因为您需要保留keys
或稍微转换值,那么最好的解决方案是使用本答案中提到的单个_.map
。 根据可读性,这也不会那么困难。
如果您想将对象的一些自定义映射(如原始 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' }, ... ];
请参阅 _.forEach https://lodash.com/docs/#forEach 的lodash
文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.