Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - One-liner to extract values from object to array

Tags:

javascript

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.

like image 982
andcl Avatar asked Oct 15 '25 03:10

andcl


2 Answers

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; }
like image 121
Ele Avatar answered Oct 16 '25 16:10

Ele


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)
like image 24
Nenad Vracar Avatar answered Oct 16 '25 17:10

Nenad Vracar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!