[英]How to get the property value from Json Data
I am getting the below Json data by calling API in Angular.我通过在 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"},
]
}
how we can convert the above JSON data into below key:value format.我们如何将上述 JSON 数据转换为以下键:值格式。 Here key is the product name and value is the total sale of that product.这里的 key 是产品名称,value 是该产品的总销售额。
{Laptop:8000,mouse:300,Printer:4000}
You can use Object.keys
like the following:您可以使用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};
now the array:现在数组:
const items = array.map( item => ({[item.name]: item.sale}));
// items -> [{Laptop: 8000}, {Mouse:300}]
Firstly , create a model/vo class for example:首先,创建一个模型/vo class 例如:
export class ProductModel() {
name?: string;
sale?: number;
company: string;
date: Date
}
Secondly , create an injectable service class for example:其次,创建一个可注入服务 class 例如:
@Injectable()
export class ProductService() {
constructor(private http: Http) {}
getProducts(): ProductModel[] {
return this.http.get<ProductModel[]>("YOUR URL", "YOUR HEADERS")} }
Finally , add to providers this service in.module.ts or component's.ts file and call in the component's.ts for example:最后,在.module.ts 或组件的.ts 文件中将此服务添加到提供者,并在组件的.ts 中调用,例如:
export class Product implements Oninit() {
data: ProductModel[]
constructor (private productService: ProductService) {}
ngOninit() { this.initProducts(); }
initProducts() {
this.data = this.productService.getProducts() }
}
This is the way that you can use from JSON to local key:value format in Angular 2+.这是您可以使用从 JSON 到 Angular 2+ 中的本地键:值格式的方式。
I hope that I could help you.我希望我能帮助你。 Sorry for my code format, this is my first stackoverflow comment.对不起我的代码格式,这是我的第一个 stackoverflow 评论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.