Tips for saving information in an array with Vue.js?

I am working on a task where I need to fetch data from an API and store only the values that are marked as "true" in a variable. The API response is listed below:

API Output Data

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

Shown below is the function I am using. It aims to filter out and save the data with a value of true into a separate array. In this code snippet, selected_data represents the API data.

    on(){
    for(let key in this.selected_data) {
        if(this.selected_data[key]) {
       // At this point, I want to collect the true values into an array.
       }
      }
     }

Answer №1

If you're looking to achieve this task, there are a few different approaches you can take. One option is to utilize the Object.keys method along with filter:

const selectedItems = this.selectedItems;
const keyArray = Object.keys(selectedItems).filter(key => selectedItems[key]);

Another way, similar to your initial code snippet, is to simply use the push method to add keys to an array:

const selectedItems = this.selectedItems;
const keyArray = [];

for (const key in selectedItems) {
  if (selectedItems[key]) {
    keyArray.push(key);
  }
}

In a Vue context, you could potentially implement this as a computed property that returns the desired array. Alternatively, you might store it in a data property by assigning the array using this.arrayName = keyArray at the end of the function.

Answer №2

You have the option to utilize 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;
        }, {});
    }
}

This piece of code will generate a new object containing only the true values from your selected_data object.

If you prefer to have an array with just the true keys, you can try the following approach:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing optimal techniques to create a JavaScript file for data retrieval in a Node.js application

I've developed a file specifically for data access purposes, where I'm keeping all my functions: const sql = require('mssql'); async function getUsers(config) { try { let pool = await sql.connect(conf ...

The AMP HTML file is unable to load due to the robots.txt file on https://cdn.ampproject.org restricting access

I've been trying to fetch and render my AMP HTML files individually, but they all seem to be encountering the same issue. According to the Search Console report, it says "Googlebot was unable to access all resources for this page. Here's a list: ...

Combining broken down values within a loop

Take a look at this image, then review the code I've provided: function addNumbers() { var inputList = document.getElementById("listInput").value.split(" "); for(i = 0; i <= inputList.length; i+=1) { document.getElementById("resul ...

What could be the reason for the HTML canvas not displaying anything after a new element is added?

How come the HTML canvas stops showing anything after adding a new element? Here is my HTML canvas, which works perfectly fine until I add a new element to the DOM: <canvas class="id-canvas", width="1025", height="600"> ...

JavaScript strangeness

I am currently working on a dynamic page loaded with ajax. Here is the code that the ' $.get' jQuery function calls (located in an external HTML page): <script type="text/javascript"> $(function() { $('button').sb_animateBut ...

An instructional HTML/JS dialogue for a linked page

On my website, there is a link that, when clicked, opens a new tab with a page that I don't control. I want to guide the user on what to do next after they are redirected to this new page ("Now please press the green button on this page"). Ideally, I ...

Exploring the contrast of && and ?? in JavaScript

My current focus is on utilizing the Logical AND && and Nullish coalescing operator ?? in handling conditional rendering of variables and values. However, I find myself struggling to fully comprehend how these operators function. I am seeking clar ...

Dynamic Component Interactions in VueJS using Mouse Events

Just starting out with Vue and other frameworks, so my approach may not be very "Vue-like". I am attempting to create a versatile button component that can have different behaviors based on a prop, in order to maintain just one button component. The desir ...

Make sure to prevent losing the global status in Vuex and VueRouter when the page is refreshed

As I develop a Single Page Application (SPA), I am utilizing Vuex to manage session states on the client side. However, I have noticed that the state resets whenever the browser is manually refreshed. Is there a way to prevent this behavior without relying ...

Creating a distinctive vue form component from scratch

I have a requirement to develop a Vue component that enables users to create or edit a mailing address. The existing component structure is as follows: <template> <v-container> <v-form ref="form" lazy-validation> <v-text-field ...

Exploring the World of Unit Testing with Jasmine and Sinon Factories

At my factory, I have implemented a getter and setter function .factory('myService', function() { var car = null; return { car: car, get: function get() { return car; }, set: function set(newCar) { car = newCar; ...

When utilizing auth0, an error occurs during the grunt build process

I successfully developed a small project using AngularJS on my local machine without encountering any issues. However, when I attempted to build the project with Grunt, everything stopped working and an error occurred: vendor.ce3c01a3.js:2 Error: [$inject ...

What is the best way to establish a default search query within the vue-multiselect component?

I have incorporated vue-multiselect into my project. You can find more information about it here. This is a snippet of my template structure: <multiselect v-model="value" :options="options" searchable="true"></multiselect> When I open the mu ...

Angular UI grid: Arranging numbers in a straight line at the decimal point

I am interested in aligning decimal numbers in Angular UI Grid as shown below. 11.293 .89 233424 .34345 I have considered different approaches such as using a cell template with aligned divs or transparent 0s. Has anyone successfully imp ...

The IsArray() function in IE8 encounters an issue where it expects an error object

I am interested to know why IE8 is having trouble with this line of code: if (isArray(obj)) When I check in the IE8 javascript console, I see the following: >>obj {...} >>typeof(obj) "object" >>Object.prototype.toString.call(obj) "[obj ...

Tips on preventing the opening of a new browser tab by using Ctrl + click

Hey there, I've got a list of products that can be selected using the Ctrl key. $(parentSelector).on("click", function (evnt) { evnt.stopImmediatePropagation(); var item = $(evnt.delegateTarget) ...

Outdated JavaScript Alert

Is it possible to use JavaScript to create an alert message in my input field when a past date is selected? I would like the warning to say "past date, please enter a valid date." <html lang="en"> <head> <meta charset="U ...

Boost the frequency of updates in Meteor.observe

When Python writes to a database (mongo) every second in the setup, Meteor.js is expected to react immediately to the new record insertion. Issue: However, the use of cursor.observe() results in the console outputting only 4-5 seconds after the new record ...

Troubleshoot my code for clustering markers on a Google map

I'm currently working on a piece of code to generate a Google map that contains 3 hidden points within one marker. The idea is that when the main marker is clicked, these points will either merge into one or expand into 3 separate markers. However, I& ...

Converting HTML to CSV using PHP

I need assistance with exporting MySQL fields to CSV. I have successfully exported all fields except the one that contains HTML content. My MySQL table is structured as follows: Name: Address: Profile: The 'Name' and 'Address' fields ...