如何将键值对对象转换为ES6中的值数组? [英] How to convert key-value pair object into an array of values in ES6?

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

问题描述

我正在开发一个React应用程序,我需要转换这样的键值对象:

I'm developing a React application where I need to convert a key-value object like this:

{
  0: 'John',
  1: 'Tim',
  2: 'Matt'
};

只有这样的值的数组:

['John', 'Tim', 'Matt']

我如何做到这一点?

const obj = {
  0: 'John',
  1: 'Tim',
  2: 'Matt'
};

const arr = /* ??? */;


推荐答案

您可以使用 Object.values 命令。

根据 docs

According to the docs.


Object.values()返回一个数组,其元素是可枚举的$ b在对象上找到$ b属性值。属性的顺序是
与手动循环遍历
对象的属性值所给出的相同

Object.values() returns an array whose elements are the enumerable property values found on the object. The ordering of the properties is the same as that given by looping over the property values of the object manually

虽然它是一个 ES2017 解决方案,但由于你使用的是反应,你可以包含 stage-0 作为预设对于 babel 并访问此功能

Although it is an ES2017 solution but since you are using react, you can include stage-0 as a preset for babel and access this functionality

var data ={
  0: 'John',
  1: 'Tim',
  2: 'Matt'
};

var newdata = Object.values(data);
console.log(newdata);

还有其他方法,如 Object.keys 它为您提供了所有键作为数组和 Object.entries 方法返回给定对象自己的可枚举属性的数组 [key,value] 对您可能也有用的对

there are other methods like Object.keys which gives you all the keys as an array and Object.entries method returns an array of a given object's own enumerable property [key, value] pairs which might also be useful to you

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

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