Reputation: 199
I've got this JSON array (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"
}
]
And I need to get just "causeoferror" object and slice it where the commas but I don't get it. I defined a new variable
public mdatacoe : string;
But when I do
this.mdatacoe = this.mdataarray.causeoferror;
In the console log I recieve undefined.
I'm pretty new to Typescript, I don't understand what I fail.
Upvotes: 2
Views: 149
Reputation: 132
Considering your variable mdatacoe is of type string and not of type string[]:
I added a duplicate of the same json object into the array to mock multiple "causeoferror" properties. The map operator accesses the "causeoferror" property and the join operator converts the array to a string.
const foo = [
{
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"
},
{
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 bar = foo.map(x => x.causeoferror).join();
console.log(bar);
If you are indeed wanting an array of type string[], then @StepUp solution should be considered instead.
Upvotes: 0
Reputation: 38209
Just take necessary object property of an array. Then you can split your string by comma sign ',':
const result = arr.map(({causeoferror}) => causeoferror.split(','));
An example:
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);
Upvotes: 1
Reputation: 91
It's an array. change your code to this: this.mdatacoe = this.mdataarray[0].causeoferror;
Upvotes: 0