如何在Angular 4中将对象转换为数组? [英] How to Convert Object to array in Angular 4?

查看:184
本文介绍了如何在Angular 4中将对象转换为数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将我的Object转换为数组,这是我的对象.

I want to convert my Object to array, here is my Object.

{5.0: 10, 28.0: 14, 3.0: 6}

我想要下面的数组

[{"type": 5.0,"value":10},{"type": 28.0,"value":14}, {"type": 3.0,"value":6}]

[{"5.0": 10},{"28.0": 14}, {"3.0": 6}]

推荐答案

通过Object.keys获取键,然后使用map函数获取所需的输出.

Get the keys via Object.keys and then use map function to get the desired output.

const obj = {5.0: 10, 28.0: 14, 3.0: 6};

const mapped = Object.keys(obj).map(key => ({type: key, value: obj[key]}));

console.log(mapped);

可以通过Object.entries数组解构提供另一种解决方案.

Another solution can be provided via Object.entries and array destructuring.

const obj = {5.0: 10, 28.0: 14, 3.0: 6};

const mapped = Object.entries(obj).map(([type, value]) => ({type, value}));

console.log(mapped);

这篇关于如何在Angular 4中将对象转换为数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆