映射对象以将对象转换为数组 [英] Mapping Object to convert object to array

查看:42
本文介绍了映射对象以将对象转换为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里有此功能:

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);
}

这里有些地方不合适:


  1. 您的第二个函数没有返回值。因此,函数调用convertObjectToList将返回未定义的函数。

  2. 您正在将 obj 的值重新分配为数组 [key ,obj [key]] ,这不是您想要执行的操作。这就是为什么得到['role',未定义]的原因,因为 obj 的最后一个键是角色,并且由于obj已被修改为数组而不是对象, obj ['role'] 将返回未定义的值。

  3. 您需要在地图内部返回一个值,否则返回数组中的每个元素

  1. Your second function does not have a return value. So function call convertObjectToList will return undefined.
  2. You are reassigning the value of obj with an array [key, obj[key]], which is not what you want to do. That is why you are getting ['role' , undefined], because the last key of obj is role, and since obj has been modified to an array an not an object, obj['role'] will return undefined.
  3. You need a return value inside the map, otherwise each element in the returned array will be undefined.

因此正确的代码如下:

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);

这篇关于映射对象以将对象转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆