0

I need to store data coming from an api in a variable. Only data that contains "true". I have given the API output below.

API Output Data

     {
      "BNG-JAY-137-003": false,
       "BNG-JAY-137-004": true, 
        "BNG-JAY-137-005": false 
       }

Below is my function. In this I need to store only data which is true in a variable. Here selected_data is a variable which contains API data.

    on(){
    for(let key in this.selected_data) {
        if(this.selected_data[key]) {
       // here I need to store data which is true in an array.
       }
      }
     }

2 Answers 2

1

There are several ways to do this. One would be to use Object.keys and filter:

const selected_data = this.selected_data
const array = Object.keys(selected_data).filter(key => selected_data[key])

Closer to your original code would be to just push the keys onto an array:

const selected_data = this.selected_data
const array = []

for (const key in selected_data) {
  if (selected_data[key]) {
    array.push(key)
  }
}

From a Vue perspective this would probably be implemented as a computed property, returning the relevant array at the end. Alternatively it might be stored in a data property, using something equivalent to this.propertyName = array at the end of the method.

Sign up to request clarification or add additional context in comments.

Comments

1

You could use a computed property:

computed: {
    valid_selected_data: function() {
        return Object.keys(this.selected_data).reduce((acc, key) => {
            if(this.selected_data[key]) {
                acc[key] = this.selected_data[key];
            }

            return acc;
        }, {});
    }
}

That code will create another object which holds the same items of your selected_data object, but only the true ones.

If you want just an array with the true keys, then try this:

computed: {
    valid_selected_data: function() {
        return Object.keys(this.selected_data).filter((key) => this.selected_data[key]);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.