简体   繁体   English

下划线 - 使用underscore.js将复杂对象转换为数组

[英]underscore - convert complex object into array using underscore.js

I am trying to format my object array into an array to be used by a component. 我试图将我的对象数组格式化为一个组件使用的数组。 I need to map the exact values of the object to the correct positions. 我需要将对象的确切值映射到正确的位置。

eg 例如

My Raw Data: 我的原始数据:

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'
                }
               ]

i would like to use underscore.js to convert this object to the following array format so I can use in my component which requires this format. 我想使用underscore.js将此对象转换为以下数组格式,以便我可以在我需要此格式的组件中使用。

Please note only name age and style are required not max . 请注意,仅限name agestyle不是max I have more undesired properties but for example above I did not want to write all. 我有更多不受欢迎的属性,但例如上面我不想写所有。

var result = [
   [ "john", "23", "expoert"],
   [ "mick", "36", "inter"],
   [ "pete", "44", "med"]
] 

I have tried pluck and map combinations, but can't seem to get the order correct in the outputted array. 我已经尝试了pluckmap组合,但似乎无法在输出的数组中获得正确的顺序。 Any help appreciated. 任何帮助赞赏。

 const rawData = [ { name: 'john', age: 23, style : 'expert' }, { name: 'mick', age: 36, style : 'inter' } ]; const result = rawData.map(Object.values); console.log(result); 

Theres no need to use a library at all. 根本不需要使用图书馆。 Or more explicitly: 或者更明确地说:

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

I would prefer this as object key/value order is not guaranteed. 我更喜欢这个,因为无法保证对象键/值顺序。

This is trivial without any library using Array#map() and Object.values() 没有任何库使用Array#map()Object.values()这是微不足道的

 var rawData = [{ name: 'john', age: 23, style: 'expert' }, { name: 'mick', age: 36, style: 'inter' }, { name: 'pete', age: 44, style: 'med' }] var res = rawData.map(o=>Object.values(o)) console.log(res) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM