简体   繁体   English

将对象文字转换为数组

[英]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);

Any help? 有什么帮助吗?

using Object.keys() and Array#map() 使用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)); 

You can do this: 你可以这样做:
1. Iterate through the object 1.遍历对象
2. Push the key and value in to array and then puh that array into answer array 2.将键和值推入数组,然后将该数组推入答案数组

  var obj = { name: 'Chris', age: 25, hobby: 'programming' }; var ans = []; for(var i in obj) { ans.push([i, obj[i]]); } console.log(ans); 

You can use Object.keys to extract all property names: 您可以使用Object.keys提取所有属性名称:

var arr=[];
Object.keys(obj).forEach(function(key){ 
     arr.push([key, obj[key]]); 
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM