2

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.

e.g.

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.

Please note only name age and style are required not 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. Any help appreciated.

2
  • 1
    Do you really need to use underscore.js? Commented Dec 6, 2017 at 18:51
  • Well that is the lib I use now. But happy if solution can be done without. I only want certain values to be mapped and not all. e.g. name, age and style, but not max or any other props which may be in my object. Commented Dec 6, 2017 at 18:58

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

1

This is trivial without any library using Array#map() and 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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.