4

I quite simple one:

I have a Javascript object with some properties whose values are arrays, with the following structure:

let obj = {emails: ["[email protected]", "[email protected]"], nickname: ["asdf"],...}

I need to get an array of arrays with only the values, like the following:

let obj2 = [["[email protected]"], ["[email protected]"], ["asdf"],...]

With Object.values(obj), I get [["[email protected]", "[email protected]"], ["asdf"],...], which is not exactly what I am looking for, but it is a good starting point...

Also, I am looking for a one-liner to do it, if possible. Any ideas? Thanks.

Aluan Haddad
32.1k10 gold badges84 silver badges95 bronze badges
asked Apr 4, 2018 at 22:20
2

2 Answers 2

5

An alternative using the function reduce.

This approach adds objects and arrays from the first level.

As you can see, this approach evaluates the type of the object.

let obj = {emails: ["[email protected]", "[email protected]"], nickname: ["asdf"]}
var result = Object.values(obj).reduce((a, c) => {
 if (Array.isArray(c)) return a.concat(Array.from(c, (r) => [r]));
 return a.concat([c]);
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

One line approach (excluding the checking for array type):

let obj = {emails: ["[email protected]", "[email protected]"], nickname: ["asdf"]},
 result = Object.values(obj).reduce((a, c) => (a.concat(Array.from(c, (r) => [r]))), []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

answered Apr 4, 2018 at 22:24
Sign up to request clarification or add additional context in comments.

3 Comments

The output does not match the way OP wanted it.
Edited the question one sec ago
Thanks. Although the other answer was a one-liner.
4

You can use Object.values to get array of values and then concat and spread syntax ... to get flat array and then map method.

let obj = {emails: ["[email protected]", "[email protected]"], nickname: ["asdf"]}
const values = [].concat(...Object.values(obj)).map(e => [e])
console.log(values)

answered Apr 4, 2018 at 22:24

2 Comments

Edited the question one sec ago
Works like a charm, and in one line. Thanks!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.