javascript - 如何从Json数据中获取属性值

标签 javascript 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"},
    ]
}

我们如何将上面的 JSON 数据转换为下面的 key:value 格式。这里的 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 }
 }

Stackblitz here !

关于javascript - 如何从Json数据中获取属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58376795/

相关文章:

Angular 2 拦截器无法正常工作

angular - 在静态和非 SPA Web 应用程序中使用 Angular 2 组件

angular - 从 Angular 发送数据时,web-api POST 主体对象始终为 null

angular - ngx-build-plus:外部不适用于 Angular 13

javascript - 对象样式属性值的数据类型

javascript - 创建自定义 html 输入

JavaScript 网络图可视化

javascript - 使用 webpack 加载 node_modules

javascript - JavaScript 的 Rails text_area 格式

javascript - 正则表达式 javascript,为什么点和逗号匹配\