0

Is it possible to convert an object to an array if it has this structure, while all fields are ignored which have an non-number field?

var obj = {
    0: 'some',
    1: 'thing',
    2: 'to convert',
    ignore: 'this'
}

result should be:

result = ['some', 'thing', 'to convert'];

with the correct order of the elements.

user3142695
  • 15,844
  • 47
  • 176
  • 332

3 Answers3

4

If it has a length property, you can use Array.from:

console.log(Array.from({
  0: 'some',
  1: 'thing',
  2: 'to convert',
  length: 3,
  ignore: 'this'
}));

Otherwise, assuming the indices are not sparse, you can iterate manually. Start from 0 and increment until you reach the end.

var obj = {
  0: 'some',
  1: 'thing',
  2: 'to convert',
  ignore: 'this'
}, array = [], i = -1;
while(++i in obj) array[i] = obj[i];
console.log(array);

In general, you would need to iterate all string properties and check if they are array indices:

function isArrayIndex(str) {
  return (str >>> 0) + '' === str && str < 4294967295
}
var obj = {
  0: 'some',
  1: 'thing',
  2: 'to convert',
  ignore: 'this'
}, array = [];
for(var key of Object.keys(obj))
  if(isArrayIndex(key)) array[key] = obj[key];
console.log(array);
Community
  • 1
  • 1
Oriol
  • 274,082
  • 63
  • 437
  • 513
0

A faster but more complex way is :

var obj = {
  0: 'some',
  1: 'thing',
  2: 'to convert',
  ignore: 'this'
}, res = [], keys = Object.getOwnPropertyNames(obj);

for(var i = 0; i < keys.length; i++)
  if(!isNaN(+keys[i]))
    res.push(obj[keys[i]]);
ClementNerma
  • 1,079
  • 1
  • 11
  • 16
-1

You can do something like this:

var obj = {
    0: 'some',
    1: 'thing',
    2: 'to convert',
    ignore: 'this'
};

var copy = {};

Object.keys(obj).forEach(e=>{
  if(!isNaN(e)) copy[e] = obj[e];
});

console.log(Object.values(copy));
Jose Hermosilla Rodrigo
  • 3,513
  • 6
  • 22
  • 38