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

Modifying iframe src using click event from a separate component in Angular 10

I am looking to dynamically update the src attribute of an iframe when the menu bar is clicked. The menu bar resides in a separate component and includes a dropdown menu for changing languages. Depending on which language is selected, I want to update the ...

Unable to trigger onClick event

The button I have with the id "jump-button" is not functioning at all. When clicked, nothing happens. I have added an alert(); to the onclick attribute to test if the button is working. However, the other two buttons (next and prev) are working perfectly ...

Attempting to modify a singular document within mongodb by leveraging node.js

const modifyTask = async (req, res) => { const { id } = req.params; let update = {}; if (req.body.taskTitle) update.taskTitle = req.body.taskTitle; if (req.body.taskContent) update.taskContent = req.body.taskContent; if (req.body.role) update. ...

Tips for transitioning the li class from active to none

Struggling with changing the li class (of Home) from 'active' to none (or another class) when clicking on the profile tab, and then changing the li class (of Profile) from none to 'active' when the profile is activated. Snippet of my c ...

Ways to eliminate project title from the URL

After removing the hash tag from the URL with $locationProvider.html5Mode(true), I attempted to address the refresh issue by adding the following code to my .htaccess file: Options +FollowSymlinks RewriteEngine On RewriteBase /test/ RewriteCond %{REQUEST_ ...

Next.js is throwing an unhandled runtime error of type TypeError, which is causing issues with reading properties of null, specifically the 'default' property

"use client" import { useKindeBrowserClient } from '@kinde-oss/kinde-auth-nextjs' import Image from 'next/image'; import React from 'react' function DashboardHeader() { const {user} = useKindeBrowserClient(); r ...

The application of textures in Three.js models is not working correctly on the entire object

I am encountering an issue with applying textures on both the top and bottom faces of a surfboard obj file. The texture seems to split in the middle instead of being applied seamlessly across the face, and it also gets applied on the inside of the mesh. I ...

What is the proper way to invoke render functions using Vue 3 composition API?

During my time with Vue 2, I would typically call render() in this manner: export default { mounted(){ ... }, render(){ ... }, methods(){ ... } } Now that I'm exploring Vue 3 and the composition API, I ...

Expanding choice by incorporating additional or default selections with ng-options

I am currently working on a tag-manager feature within an angular form that utilizes two dropdown menus (in this example, a food category and a specific item). The functionality I am aiming for is when a user selects a food category, the item dropdown shou ...

What is the best way to sequentially read various sections of a file in vue.js?

I am currently working on a browser tool that analyzes a large file and provides statistics based on its content. The tool randomly selects k parts of the file for processing, treating each part individually. As each part is processed, an object is update ...

Return the information from Node.js to the JavaScript on the client side

My goal is to establish a fetch connection from client-side JS to the server Node.JS. When a person clicks on a button in HTML, it triggers a search in the MongoDB database on the server side. Once the element is found, I am unsure how to send that informa ...

Encountering difficulties obtaining server response while utilizing dropzone.js version 4

I am currently using dropzone.js version 4 to facilitate file uploads from a webpage to my server. While the upload process is functioning properly, I am encountering difficulty in retrieving the server response. It should be noted that I am creating the D ...

Challenges with the "//" syntax in UNIX

$('#lang_choice1').each(function () { var lang = $(this).val(); $('#lang_files').empty(); $.ajax({ type: "POST", url: '< ...

What is the most effective way to access nested elements by index in JavaScript?

I am looking to design a user-friendly form that presents questions for users to navigate, revealing different answers/questions based on their responses. For example: var json = { "Did you restart the computer?": [ { ...

Show various Vuejs components specifically tailored for mobile browsers

I am currently working on a Single Page Application (SPA) using Vue 2.0. The components I have created so far are optimized for "desktop" browsers, including: Main.vue, ProductList.vue, ProductDetail.vue, Now, I need to create a separate set of component ...

JavaScript Pagination and JSON Concerns in Coding Techniques

Currently, I am pre-caching a dataset with a maximum limit of 500. The Ajax request fetches all the data at once, allowing for front loading and pagination. Everything works fine this way. However, we are in the process of transitioning our backend archit ...

Protractor Throws Element Visibility Issue

When attempting to check a checkbox in the UI, I encounter an "ElementNotVisibleError: element not visible" error. Strangely, I am able to successfully capture and click the checkbox using the console in Chrome developer tools. Has anyone else experience ...

Tips on how to choose all elements that do not include a specific value or group of values in cypress

Here's my situation: selector: ".list > div" const velue = [6, 9, 21] Each div contains a different value. I want to remove elements that contain a specific value, then select the first remaining element and click on it. It should look ...

Unlocking the potential of Vue within shadow dom environments

I am facing an issue with a shadow DOM that includes the root element and a Vue component. <template> <div class="container"> <div id="app"></div> </div> <script src="http://my-site.com/app/js/vue-compo ...

The assignment of type 'string' to type 'UploadFileStatus | undefined' is not permissible

import React, { useState } from 'react'; import { Upload } from 'antd'; import ImgCrop from 'antd-img-crop'; interface uploadProps{ fileList:string; } const ImageUploader:React.FC <uploadProps> ...