将对象文字转换为数组 [英] convert an object literal into an array
本文介绍了将对象文字转换为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在这里有一个数组对象:
I have an array object here:
var obj = {
name: 'Chris',
age: 25,
hobby: 'programming'
};
我需要一个函数,即使不知道键或值,也可以将对象文字转换为数组数组:
I need a function that will convert an object literal into an array of arrays even without knowing the key or the value like this:
[['name', 'Chris'], ['age', 25], ['hobby', 'programming']]
所以我创建了一个函数来做到这一点.但是,我不确定从哪里开始使我能够将它们合并.
So I created a function to do that. However I am not sure where to start to enable me to merge them.
function convert(obj) {
var array = [];
}
convert(obj);
有帮助吗?
推荐答案
使用 Object.keys()
和 Array#map()
var obj = {
name: 'Chris',
age: 25,
hobby: 'programming'
};
function convert(obj) {
return Object.keys(obj).map(k => [k, obj[k]]);
}
console.log(convert(obj));
这篇关于将对象文字转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文