我正在开发一个 React 应用程序,我需要像这样转换一个键值对象:
{
0: 'John',
1: 'Tim',
2: 'Matt'
};
对于像这样的值的数组:
['John', 'Tim', 'Matt']
我该如何做到这一点?
const obj = {
0: 'John',
1: 'Tim',
2: 'Matt'
};
const arr = /* ??? */;
最佳答案
您可以使用 Object.values
.
The
Object.values()
method returns an array of a given object's own enumerable property values, in the same order as that provided by afor...in
loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
var object = { 0: 'John', 1: 'Tim', 2: 'Matt' },
array = Object.values(object);
console.log(array);
使用 ES6,您可以使用
Array.from
并对值使用回调。var object = { 0: 'John', 1: 'Tim', 2: 'Matt' },
array = Array.from(Object.keys(object), k => object[k]);
console.log(array);
关于javascript - 如何将键值对对象转换为 ES6 中的值数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45411208/