typescript 将 Json 字符串转换为角度为 6 的 json 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51765567/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert Json String to json Arrays in angular 6
提问by nidhi
Hi I want to convert the RestController Response which is in Json String to json array here is my json array sting which i have printed in console.
嗨,我想将 Json 字符串中的 RestController 响应转换为 json 数组,这里是我在控制台中打印的 json 数组字符串。
'{"Impressions":["Budget","CTR","Campaign","Campaign state","Clicks","Conv. rate"],"Clicks":["Budget","CTR","Campaign","Campaign state","Clicks","Conv. rate"],"Revenue":["Budget","CTR","Campaign","Campaign state","Clicks","Conv. rate"]}'
I want to convert it to json array so that i can iterate it,
我想将它转换为 json 数组,以便我可以迭代它,
My requirement is to iterate the array and print key as label and value as slect options
我的要求是迭代数组并打印键作为标签和值作为选择选项
Example:
例子:
Impression as label and "Budget","CTR","Campaign","Campaign state","Clicks","Conv. rate" as select options.
印象作为标签,“预算”、“点击率”、“广告系列”、“广告系列状态”、“点击次数”、“转化率”作为选择选项。
Here is my code for iteration
这是我的迭代代码
<div>
<form *ngFor ="let map of mapper">
<mat-form-field>
<mat-select placeholder="{{map}}">
<!--<mat-option>None</mat-option>-->
<mat-option *ngFor="let option of map" [value]="option">
{{option}}
</mat-option>
</mat-select>
</mat-form-field>
</form>
</div>
my .ts class
我的 .ts 类
this.clientService.getHeaders().subscribe(
(res) => {
console.log(res);
let resSTR = JSON.stringify(res);
let resJSON = JSON.parse(resSTR);
this.mapper=Array.of(resJSON._body);
console.log(this.mapper);
this.ismapped=false;
}
);
回答by DEVCNN
this.clientService.getHeaders().subscribe(
(res) => {
console.log(res);
let result= <any>res;
this.mapper= result;
console.log(this.mapper);
this.ismapped=false;
}
);
No need to go into stringifying and then parsing. Just cast the response to anyand then you can use it as an array.
无需进行字符串化然后解析。只需将响应转换为any,然后您就可以将其用作数组。
回答by Alex Link
let str = '{"Impressions":["Budget","CTR","Campaign","Campaign state","Clicks","Conv. rate"],"Clicks":["Budget","CTR","Campaign","Campaign state","Clicks","Conv. rate"],"Revenue":["Budget","CTR","Campaign","Campaign state","Clicks","Conv. rate"]}'
Object.keys(JSON.parse(str)).map(arr => {
return `${arr}: ${JSON.parse(str)[arr].join(', ')}`;
});
Do whatever logic you want in return statement. Return it as a string, or as an array, or as an object.
在 return 语句中做任何你想要的逻辑。将其作为字符串、数组或对象返回。