[英]Javascript - One-liner to extract values from object to array
I quite simple one: 我很简单:
I have a Javascript object with some properties whose values are arrays, with the following structure: 我有一个Javascript对象,其中一些属性的值是数组,具有以下结构:
let obj = {emails: ["xxx@yyy.com", "qqq@www.com"], nickname: ["asdf"],...}
I need to get an array of arrays with only the values, like the following: 我需要获得一个只包含值的数组数组,如下所示:
let obj2 = [["xxx@yyy.com"], ["qqq@www.com"], ["asdf"],...]
With Object.values(obj)
, I get [["xxx@yyy.com", "qqq@www.com"], ["asdf"],...]
, which is not exactly what I am looking for, but it is a good starting point... 使用
Object.values(obj)
,我得到[["xxx@yyy.com", "qqq@www.com"], ["asdf"],...]
,这不是我想要的,但这是一个很好的起点......
Also, I am looking for a one-liner to do it, if possible. 另外,如果可能的话,我正在寻找一个单行代码。 Any ideas?
有任何想法吗? Thanks.
谢谢。
An alternative using the function reduce
. 使用函数
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: ["xxx@yyy.com", "qqq@www.com"], 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: ["xxx@yyy.com", "qqq@www.com"], 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. 您可以使用
Object.values
获取值数组,然后concat
并传播语法...
以获得平面数组,然后使用map
方法。
let obj = {emails: ["xxx@yyy.com", "qqq@www.com"], nickname: ["asdf"]} const values = [].concat(...Object.values(obj)).map(e => [e]) console.log(values)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.