【问题标题】:Get array object with specific properties axios获取具有特定属性 axios 的数组对象
【发布时间】:2020-10-25 21:46:23
【问题描述】:

我正在通过 axios 从 API 调用中获取 JSON,目前正在使用 vue 显示 JSON。

这是来自控制台的 JSON 对象:

0:
  category_id: "categ1"
  item_name: "item1"
  price: 100
  stock: 155
1:
  category_id: "categ2"
  item_name: "item2"
  price: 100
  stock: 155
2:
  category_id: "categ1"
  item_name: "item3"
  price: 100
  stock: 155
3:
  category_id: "categ3"
  item_name: "item4"
  price: 100
  stock: 155

这是我的 vue 挂载函数(我正在使用 axios):

mounted () {    
  axios.get('link_for_api_endpoint', {  
    headers : { 
      Authorization: 'Bearer ' + access_token,
    },
    params: {
      limit: 250
    }
  })
    .then((response) => {
      this.data = response.data.items;
      //console.log(response);  
      $("#ldr").hide(); 
      removeLoader();   
    })  
    .catch(function (error) {
      console.log(error);   
    })  
    .then(function () { 

    }); 
}

我想要做的是我只想获取具有类别值“categ1”的数据,而不是整个 json 对象。我如何做到这一点?

【问题讨论】:

  • jquery?为了什么?

标签: javascript vue.js axios


【解决方案1】:

如果响应是对象数组,您可以使用Array.prototype.filter。

const result = response.filter(item => item.category_id === 'categ1');

在结果数组中,您将拥有以categ1 作为categoryId 的对象

【讨论】:

  • 你不需要解析它 axios 为你做它
  • 感谢您的关注,更新了使用filter 而不是find 的答案并删除了JSON.parse
猜你喜欢
  • 2018-07-20
  • 2023-02-26
  • 1970-01-01
  • 1970-01-01
  • 2013-01-28
  • 1970-01-01
  • 1970-01-01
  • 2016-09-16
  • 2019-05-20
相关资源
最近更新 更多