![](/img/trans.png)
[英]How to get the data from a async function and used that as a property value for a json on another asyn function?
[英]How to get the property value from Json Data
我通过在 Angular 中调用 API 得到以下 Json 数据。
{
"Product":[
{ "name":"Laptop", "sale":3000, "company":"hp", "date":"12 Oct"},
{ "name":"Mouse", "sale":300, "company":"lenovo", "date":"13 Oct"},
{ "name":"Laptop", "sale":5000, "company":"dell", "date":"12 Oct"},
{ "name":"Printer", "sale":4000, "company":"lenovo", "date":"14 Oct"},
]
}
我们如何将上述 JSON 数据转换为以下键:值格式。 这里的 key 是产品名称,value 是该产品的总销售额。
{Laptop:8000,mouse:300,Printer:4000}
您可以使用Object.keys
,如下所示:
result = {};
items = {
Product: [
{ name: "Laptop", sale: 3000, company: "hp", date: "12 Oct" },
{ name: "Mouse", sale: 300, company: "lenovo", date: "13 Oct" },
{ name: "Laptop", sale: 5000, company: "dell", date: "12 Oct" },
{ name: "Printer", sale: 4000, company: "lenovo", date: "14 Oct" }
]
};
ngOnInit(): void {
Object.keys(this.items.Product).map(key => {
const name = this.items.Product[key].name;
const sale = this.items.Product[key].sale;
if (this.result.hasOwnProperty(name)) {
this.result[name] = this.result[name] + sale;
} else {
this.result[name] = sale;
}
});
console.log(this.result); // { "Laptop": 8000, "Mouse": 300, "Printer": 4000 }
}
const item = { "name":"Laptop", "sale":3000, "company":"hp", "date":"12 Oct"}
const converted = {[item.name]: item.sale};
现在数组:
const items = array.map( item => ({[item.name]: item.sale}));
// items -> [{Laptop: 8000}, {Mouse:300}]
首先,创建一个模型/vo class 例如:
export class ProductModel() {
name?: string;
sale?: number;
company: string;
date: Date
}
其次,创建一个可注入服务 class 例如:
@Injectable()
export class ProductService() {
constructor(private http: Http) {}
getProducts(): ProductModel[] {
return this.http.get<ProductModel[]>("YOUR URL", "YOUR HEADERS")} }
最后,在.module.ts 或组件的.ts 文件中将此服务添加到提供者,并在组件的.ts 中调用,例如:
export class Product implements Oninit() {
data: ProductModel[]
constructor (private productService: ProductService) {}
ngOninit() { this.initProducts(); }
initProducts() {
this.data = this.productService.getProducts() }
}
这是您可以使用从 JSON 到 Angular 2+ 中的本地键:值格式的方式。
我希望我能帮助你。 对不起我的代码格式,这是我的第一个 stackoverflow 评论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.