如何使用 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 和其他方法来组合对象。
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
plain 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);
如果您还想保留密钥,请使用 和
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)
。
Object.values、lodash values 和 toArray 执行此操作。并保留键 map 和 spread 运算符 玩得很好:
// 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>
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
将它们设置为值
Object.values
(ES-2017 中)
Object.entries
然后
map
每个键/值对(在 ES-2017 中)
for...in
循环并使用每个键来设置值
lodash
(并假设有人已经使用它),那么你不需要考虑太多关于版本、方法支持和错误处理(如果没有找到这些)。还有其他 lodash 解决方案,例如
_.values
(对于特定用途更具可读性),或者获取对然后映射等等。但如果您的代码需要灵活性,您可以在将来更新它,因为您需要保留
keys
或稍微转换值,那么最好的解决方案是使用单个
_.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 的
lodash
文档https://lodash.com/docs/#forEach
我们不应该使用_.values,我们应该使用导入方法并使用:
import { values } from 'lodash';
enum ProductCode {
ORR = 'ORR',
MMHS = 'MMHS',
STTU = 'STTU',
OOS = 'OOS'
}
const arr = values(ProductCode);
console.log(arr);