我在这里有此功能:
var obj = { name: 'Holly', age: 35, role: 'producer' }; function convertObjectToList(obj) { return Object.keys(obj).map(k => [k, obj[k]]); } convertObjectToList(obj);此函数将数组转换为obj。因此,如果我的obj在上面,我会得到这样的东西:
This function converts an array to obj. So if I have that obj above i'll get something like this:
[['name', 'Holly'], ['age', 35], ['role', 'producer']]现在我想要在这里重点:
Now I want to focus here:
return Object.keys(obj).map(k => [k, obj[k]]);简而言之, Object.keys 返回给定对象自己的可枚举属性的数组,并将映射迭代到数组中,以此类推。我试图理解上面的箭头功能,并尝试将其分解为更简单易懂的代码。
Breaking it down, Object.keys basically returns an array of a given object's own enumerable properties and map iterates in an array and so something with it. I am trying to understand the arrow function above and try to break it down into simpler understandable code for me.
function convertObjectToList(obj) { Object.keys(obj).map(function(key){ obj = [key, obj[key]]; }); console.log(obj); }但是这个没有用。相反,它仅返回[ role,未定义]。
But this one did not work. Instead it only returns ["role", undefined].
有没有人可以让我用通俗易懂的术语理解我并分解代码,以便我可以清楚地理解。
Is there anyone out there who can make me understand in laymans term and break down the code so I would understand it clearly.
对不起,我是初学者。否。
Sorry I am beginner. Noob.
推荐答案这是您的第二个功能:
function convertObjectToList(obj) { Object.keys(obj).map(function(key){ obj = [key, obj[key]]; }); console.log(obj); }这里有些地方不合适:
因此正确的代码如下:
var obj = { name: 'Holly', age: 35, role: 'producer' }; function convertObjectToList(obj) { return Object.keys(obj).map(function(key){ let currElement = [key, obj[key]]; return currElement }); } var res = convertObjectToList(obj); console.log(res);
更多推荐
映射对象以将对象转换为数组
发布评论