使用ES6功能将对象转换为数组 [英] Converting Object to Array using ES6 features
本文介绍了使用ES6功能将对象转换为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出一个javascript对象,如何在ECMAScript-6中将其转换为数组?
Given a javascript object, how can I convert it to an array in ECMAScript-6 ?
例如,给定:
var inputObj = {a:'foo', b:[1,2,3], c:null, z:55};
预期输出为:
['foo', [1,2,3], null, 55]
结果中元素的顺序对我来说并不重要.
The order of the elements in the result is not important to me.
推荐答案
使用(ES5) 键
和
Use (ES5) Array::map
over the keys
with an arrow function (for short syntax only, not functionality):
let arr = Object.keys(obj).map((k) => obj[k])
真正的ES6风格是编写一个生成器,并将可迭代的值转换为数组:
True ES6 style would be to write a generator, and convert that iterable into an array:
function* values(obj) {
for (let prop of Object.keys(obj)) // own properties, you might use
// for (let prop in obj)
yield obj[prop];
}
let arr = Array.from(values(obj));
遗憾的是,没有对象迭代器使其成为ES6本机
Regrettably, no object iterator has made it into the ES6 natives.
这篇关于使用ES6功能将对象转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文