Reputation: 3548
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.
Upvotes: 4
Views: 2107
Reputation: 33726
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; }
Upvotes: 5
Reputation: 122057
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)
Upvotes: 4