如何将键从对象推送到数组?
假设我有以下对象 obj
:
obj = {
'key1' : ['1','2','3'],
'key2' : ['1','2','9'],
'key3' : ['1','3','5']
}
如何将 obj
转换为如下所示的两个数组?
allOfTheKeys = ['key1','key2','key3']
allOfTheArrays = ['1','2','3','5','9']
Suppose I have the following object obj
:
obj = {
'key1' : ['1','2','3'],
'key2' : ['1','2','9'],
'key3' : ['1','3','5']
}
How can I transform obj
into two arrays that look like the following?
allOfTheKeys = ['key1','key2','key3']
allOfTheArrays = ['1','2','3','5','9']
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
实际上
,在 jQuery 中,您可以使用
each()
更简洁地做到这一点(警告,这不是经过测试的代码):好的,您不想重复,请添加
Something like
Actually, in jQuery you can do it more concisely using
each()
(warning, this isn't tested code):Okay, you don't want repeats, add in
正如我所看到的,其他答案返回重复的值。这里有解决方案(已测试):
如果有人想知道
nonRepeatedElems
是什么,它是数组值的哈希表,其键是数组元素值。所以我没有得到重复的元素。如果您希望对值进行排序,只需最后调用
allOfTheArrays.sort();
即可。编辑:@float,这里有一个更容易理解的解决方案:
As I saw, other answers return repeated values. Here you have the solution (tested):
If someone's wondering what
nonRepeatedElems
is, it's a hash table for the array values, whose key is the array element value. So I don't get repeated elements.If you want your values to be ordered, just call
allOfTheArrays.sort();
in the end.EDIT: @float, Here you have a more understandable solution: