首页 > 解决方案 > 从 JSON 中获取元素并对其进行切片

问题描述

我有这个 JSON 数组(mdataarray)

[
{
"frumain" : "ESC",
"fruother" : "PAC or SEP or SPCB",
"connector" : "SE3 or SE7",
"sensor" : "ECHC, ECPC, ECCC, PCEC",
"motorsolenoid" : "ESCM",
"causeoferror" : "004, 101, 102, 103, 104, 106, 107, 108, 110, 111, 210, 211, 212, 213, 301, 302, 303, 304, 305, 306, 307, 312"
}
]

而且我只需要获取“causeoferror”对象并将其切片到逗号的位置,但我不明白。我定义了一个新变量

public mdatacoe : string;

但是当我这样做时

this.mdatacoe = this.mdataarray.causeoferror;

在控制台日志中,我收到未定义的信息。

我对 Typescript 很陌生,我不明白我失败了什么。

标签: arraysangulartypescriptionic-framework

解决方案


只需获取数组的必要对象属性。然后你可以用逗号符号','分割你的字符串:

const result = arr.map(({causeoferror}) => causeoferror.split(','));

一个例子:

let arr = [
    {
        "frumain": "ESC",
        "fruother": "PAC or SEP or SPCB",
        "connector": "SE3 or SE7",
        "sensor": "ECHC, ECPC, ECCC, PCEC",
        "motorsolenoid": "ESCM",
        "causeoferror": "004, 101, 102, 103, 104, 106, 107, 108, 110, 111, 210, 211, 212, 213, 301, 302, 303, 304, 305, 306, 307, 312"
    }
];

const result = arr.map(({causeoferror}) => causeoferror.split(','));
console.log(...result);


推荐阅读