How to convert key-value pair object into an array of values in ES6?

落花浮王杯 提交于 2019-12-01 13:39:21

You can make use of Object.values command.

According to the docs.

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

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

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

You could use 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 a for...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);

With ES6, you could use Array.from and use a callback for the values.

var object = { 0: 'John', 1: 'Tim', 2: 'Matt' }, 
    array = Array.from(Object.keys(object), k => object[k]);
    
console.log(array);
const obj = {
  0: 'John',
  1: 'Tim',
  2: 'Matt'
};

const arr = [];
for(let key in obj){
  arr.push(obj[key]);
}

While you have numerical keys and in an order without gaps, you could use Object.assign with an array as target and the given object as source.

var object = { 0: 'John', 1: 'Tim', 2: 'Matt' }, 
    array = Object.assign([], object);
    
console.log(array);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!