JaChNo
JaChNo

Reputation: 1563

get value from a filtered array of objects

I have an array of objects each object contains a name property and a value property

enter image description here

what I want to do is return the value for the specified name

I am using a computed property

computed: {
    statAlertCount() {
      var stat = this.siteStatistics.filter(item => {
        console.log(item);
        return item.name == "site_alert_count";
      });
      console.log(stat[0]);
    }
  }

this code returns and object 'stat' which i can console out. it looks like this.

enter image description here

but if I try to access the value using stat[0].stat then I get the following error

app.js?id=f37d3d495892e39c6054:85474 [Vue warn]: Error in render: "TypeError: Cannot read property 'stat' of undefined"

Upvotes: 1

Views: 48

Answers (2)

Bohdan Sviripa
Bohdan Sviripa

Reputation: 451

An alternative solution using find:

computed: {
  statAlertCount() {
    const statItem = this.siteStatistics.find(item => item.name == "site_alert_count");
    return statItem ? statItem.stat : "";
  }
}

Upvotes: 0

Will Jenkins
Will Jenkins

Reputation: 9787

I think you just need to return:

computed: {
  statAlertCount() {
    var stat = this.siteStatistics.filter(item => item.name === "site_alert_count");

    return stat.length > 0 ? stat[0].stat : '';
  }
}

Upvotes: 5

Related Questions