【问题标题】:How to convert nested array to normal array and change types?如何将嵌套数组转换为普通数组并更改类型?
【发布时间】:2018-12-13 11:31:30
【问题描述】:

我的数组结构如下:

[{Id: Number, Attributes: {Name: String, Age: String, Height: String}}]

我想把它转换成:

[{Id: Number, Name: String, Age: Number, Height: Number}]

另外如何将"2018-12-12 09:19:40" 转换为 Date 对象?同时转换整个数组。

如何做到这一点?是否使用 lodash。

【问题讨论】:

  • @Justcode 干什么用的?

标签: javascript angular typescript lodash


【解决方案1】:

您可以使用 map 和扩展语法 ...

const data = [{Id: 'Number', Attributes: {Name: 'String', Age: 'String', Height: 'String'}}]
const res = data.map(({Attributes, ...rest}) => ({...rest, ...Attributes}))
console.log(res)

要转换数据类型,您可以使用一些嵌套解构。

const data = [{Id: 'Number', Attributes: {Name: 'String', Age: '20', Height: '123'}}]
const res = data.map(({Attributes: {Age, Height, ...attr}, ...rest}) => ({
  ...rest,
  ...attr,
  Age: +Age,
  Height: +Height
}))
console.log(res)

【讨论】:

  • 但是如何转换数据类型呢?
  • 你能举个例子吗?
  • 你在用猫鼬吗?纯javascript中没有Id类型
  • @Chris K. 对不起,我不确定你在问什么,如果输入中的 id 类型是数字,它将保持数字,如您在此处看到的 jsfiddle.net/sfu9kt5h/74,但没有 ID 类型javascript。
  • 但是假设您只想将 Id 从数字转换为字符串,那么您可以这样做jsfiddle.net/sfu9kt5h/75
【解决方案2】:

如果要将对象转换为数组(更改类型),可以尝试 Object.entries(); 在 Es2017 中有一个属性在这些情况下很有用,(Object.entries());

const cars = {"BMW": 3, "Tesla": 2, "Audi": 5}
const map = new Map(Object.entries(cars));
console.log(map);

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2021-06-13
    • 2015-02-05
    • 2020-01-14
    • 1970-01-01
    • 1970-01-01
    • 2021-10-03
    • 1970-01-01
    • 2022-10-14
    • 1970-01-01
    相关资源
    最近更新 更多