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.
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.
Share Improve this question edited Apr 5, 2018 at 14:10 Aluan Haddad 31.9k10 gold badges83 silver badges95 bronze badges asked Apr 4, 2018 at 22:20 andclandcl 3,5587 gold badges40 silver badges67 bronze badges 2- 1 Possible duplicate of Best way to flatten JS object (keys and values) to a single depth array – Obsidian Age Commented Apr 4, 2018 at 22:22
- This is not the same, I only need the values (not the keys), and each one in a separate array... – andcl Commented Apr 4, 2018 at 22:53
2 Answers
Reset to default 5An 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; }
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)