我正在尝试将我的对象数组格式化为一个数组以供组件使用。我需要将对象的确切值映射到正确的位置。
例如
我的原始数据:
var rawData = [
{ name: 'john',
age: 23,
style : 'expert',
max : 'none'
},
{ name: 'mick',
age: 36,
style : 'inter',
max : 'none'
},
{ name: 'pete',
age: 44,
style : 'med',
max : 'none'
}
]
我想使用 underscore.js将此对象转换为以下数组格式,以便我可以在需要此格式的组件中使用。
请注意只有 name
age
和 style
是必需的,max
不是必需的。我有更多不需要的属性,但例如上面我不想写所有。
var result = [
[ "john", "23", "expoert"],
[ "mick", "36", "inter"],
[ "pete", "44", "med"]
]
我尝试了 pluck
和 map
组合,但似乎无法在输出数组中获得正确的顺序。任何帮助表示赞赏。
最佳答案
const rawData = [
{ name: 'john', age: 23, style : 'expert' },
{ name: 'mick', age: 36, style : 'inter' }
];
const result = rawData.map(Object.values);
console.log(result);
根本不需要使用库。或者更明确地说:
const rawData = [
{ name: 'john', age: 23, style : 'expert' },
{ name: 'mick', age: 36, style : 'inter' }
];
const result = rawData.map(({name, age, style}) => [name, age, style]);
console.log(result);
我更喜欢这个,因为不能保证对象键/值顺序。
关于javascript - underscore - 使用 underscore.js 将复杂对象转换为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47681449/