如果对象具有这种结构,是否可以将其转换为数组,而忽略具有非数字字段的所有字段,是否可以将其转换为数组?
var obj = {
0: 'some',
1: 'thing',
2: 'to convert',
ignore: 'this'
}
结果应该是:
result = ['some', 'thing', 'to convert'];
具有正确的元素顺序。
如果具有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);
通常,您需要迭代所有字符串属性,并检查它们是否为数组索引:
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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句