映射对象以将对象转换为数组

编程入门 行业动态 更新时间:2024-10-24 16:25:47
本文介绍了映射对象以将对象转换为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在这里有此功能:

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

这里有些地方不合适:

  • 您的第二个函数没有返回值。因此,函数调用convertObjectToList将返回未定义的函数。
  • 您正在将 obj 的值重新分配为数组 [key ,obj [key]] ,这不是您想要执行的操作。这就是为什么得到['role',未定义]的原因,因为 obj 的最后一个键是角色,并且由于obj已被修改为数组而不是对象, obj ['role'] 将返回未定义的值。
  • 您需要在地图内部返回一个值,否则返回数组中的每个元素
  • Your second function does not have a return value. So function call convertObjectToList will return undefined.
  • 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.
  • 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);

    更多推荐

    映射对象以将对象转换为数组

    本文发布于:2023-11-30 12:12:32,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1649900.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:对象   数组   转换为

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!