删除非数字字段名称时将对象转换为数组

时间:2016-07-02 17:41:39

标签: javascript

如果对象具有此结构,是否可以将对象转换为数组,而忽略所有具有非数字字段的字段?

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

结果应为:

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

具有正确的元素顺序。

3 个答案:

答案 0 :(得分:4)

如果它具有length属性,则可以使用Array.from



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




否则,假设索引不是稀疏的,您可以手动迭代。从0开始并递增,直到结束。



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




通常,您需要迭代所有字符串属性和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);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

更快但更复杂的方式是:

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

答案 2 :(得分:-1)

您可以这样做:

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