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

查看:33
本文介绍了如何将键值对对象转换为 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 命令.

根据文档.

According to the docs.

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

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 解决方案,但由于您使用的是 React,您可以将 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天全站免登陆