What could be causing the strange output from my filtered Object.values() function?

In my Vue3 component, I created a feature to showcase data using chips. The input is an Object with keys as indexes and values containing the element to be displayed.

Here is the complete code documentation:

<template>
  <div class="row">
    <div>a fixed entry during debug</div>
    <q-chip v-for="alert in failedAlerts" :key="alert.Id" color="orange">{{ alert.FullTargetName }}</q-chip>
  </div>
</template>

<script lang="ts">

import {toRef, Ref, computed, watch} from 'vue'
import log from 'assets/log'

interface Alert {
  IsOK: boolean;
  FullTargetName: string,
  Why: string,
  Extra: string,
  Id: string,
  When: string
}

function alertFactory(): Alert {
  return {
    Extra: '', FullTargetName: 'dummy alert', Id: '0', IsOK: false, When: '0', Why: 'dummy alert explanation',
  }
}

export default {
  name: 'Homemonitor',
  // the complete props definitiin is temporarily commented out to make sure the problem
  // does not come from here
  // props: {
  //   alerts: {
  //     type: Object,
  //     default: () => alertFactory(),
  //   },
  // },
  props: ['alerts'],
  setup(props) {
    // TODO: review the global eslint exclusions below
    /* eslint-disable @typescript-eslint/no-unsafe-call */
    /* eslint-disable @typescript-eslint/no-unsafe-return */
    /* eslint-disable @typescript-eslint/no-unsafe-member-access */

    let failedAlerts = computed(() => Object.values(toRef(props, 'alerts')).filter((x: Alert) => !x.IsOK))

    return {failedAlerts}
  },
}
</script>

<style scoped>

</style>

Upon inspecting DevTools → Vue, I noticed that failedAlerts wasn't the expected neat Array of Alert, but rather

https://i.sstatic.net/zRNI9m.png

alert in both props and setup → failedAlerts → alerts` contains the correct content

https://i.sstatic.net/Al3N6m.png

The issue arises because Object.values() should have returned an Array of values from the object (filtered).

Based on the provided data, it should look something like this: (IsOK being true would filter it out)

// failedAlerts

[
  {
    "IsOK":true,
    "FullTargetName":"bind → Amazon_Fire",
    "Why":"",
    "Extra":"",
    "Id":"8bd3b2c7fe73ea6c0d0aac324baaa354",
    "When":"2021-08-19T13:02:33+02:00"
  },
(...)
]

What could be causing failedAlerts to have the current structure?


UPDATE: After carefully examining the types in my code (thanks to @EstusFlask for the help), I believe I have resolved the issues in the <script> section.

<script lang="ts">

import {computed, Ref, toRef, watch} from 'vue'

interface Alert {
  IsOK: boolean;
  FullTargetName: string,
  Why: string,
  Extra: string,
  Id: string,
  When: string
}

function alertFactory(): Record<string, Alert> {
  return {
    'dummy index':
        {
          Extra: '', FullTargetName: 'dummy alert', Id: '0', IsOK: false, When: '0', Why: 'dummy alert explanation',
        },
  }
}

export default {
  name: 'Homemonitor',
  props: {
    alerts: {
      type: Object,
      required: true,
      // default: () => alertFactory(),
    },
  },
  // props: ['alerts'],
  setup(props) {
    // TODO: review the global eslint exclusions below
    /* eslint-disable @typescript-eslint/no-unsafe-call */
    /* eslint-disable @typescript-eslint/no-unsafe-return */
    /* eslint-disable @typescript-eslint/no-unsafe-member-access */

    let failedAlerts = computed(() => Object.values(props.alerts as Ref<Record<string, Alert>>).filter((x: Alert) => !x.IsOK))

    return {failedAlerts}
  },
}
</script>

Answer №1

toRef retrieves a reference of the specified type

interface Ref<T> {
  value: T
}

When Object.values is applied to this reference, it returns an array containing the values of that type.

To access the actual values stored within the object, utilize toRef(...).values.

Given that props.alert is reactive by default, implementing toRef may not be necessary (as others have also pointed out). Instead, consider using Object.values(props.alerts)

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

Angular 5 error: The property you are trying to access is not defined in

I've been working on a simple class and I'm stuck trying to figure out why the "currentHost" variable is showing as non-existent. export class AppModule { public static currentHost: string = 'http://localhost:8080/'; constructor() ...

Sorry, the provided text is already unique as it is an error message

I'm currently using the react-highlight-words package to highlight text inputted into a textbox After checking out the react-highlight-words documentation, I noticed that they are using searchWords as an array. https://www.npmjs.com/package/react-high ...

JavaScript: A dynamic table is created with columns populated by JSON data. The row structure is compromised

On my webpage, I pull in two sets of JSON data: 1) warehouses and 2) items. After receiving an Ajax search response from my view, I need to dynamically generate the TDs of a table based on the warehouses information. The goal is to populate all TDs for ev ...

Is the inclusion of @vue/composition-api in devDependencies warranted?

Is it recommended to add @vue/composition-api to the dependencies section of the package.json instead of devDependencies? I noticed that on the npm registry it is listed under dependencies. ...

Implementing variable mocking with Jest for Vuex store actions

I am working with a JavaScript code snippet that looks like this: const Repository = axios.create( { baseURL: process.env.VUE_APP_API_HOST } ); const state = { ... } const getters = { ... } const mutations = { ... } const actions = { fetch: async ( ...

What is the reason behind the ability to reassign an incompatible function to another in TypeScript?

I discovered this question while using the following guide: https://basarat.gitbooks.io/typescript/content/docs/types/type-compatibility.html#types-of-arguments. Here is an example snippet of code: /** Type Heirarchy */ interface Point2D { x: number; y: ...

Tips on modifying the interface based on the selected entry using jQuery

I am attempting to display a text when different options are selected from the dropdown list. Here is the code for the drop-down list: <div class="dropdown"> <select class="form-control" id="ltype" name="ltype"> <option value=""&g ...

tsconfig.json respects the baseUrl for absolute imports inconsistently

While using create-react-app, I have noticed that absolute imports work in some files but not in others. Directory Layout . +-- tsconfig.js +-- package.json +-- src | +-- components | | +-- ui | | | +-- Button | | | | +-- Button.tsx | ...

Issue: Generated JavaScript files not visible in Visual Studio when using TypeScript.Explanation: When working with

Is there a way to locate the JavaScript files generated from the TypeScript file in Visual Studio 2015? It seems that although the JavaScript files are present in File Explorer, they are not visible in the solution explorer. I attempted to add the _refer ...

Ways to activate a watcher even when it is assigned to the same newVal

Currently, I am utilizing the vue3 framework with the options api You can refer to the demonstration provided in the following stackbiltz link here In my setup, there is a child-component that features a button. Upon clicking this button, the refresh met ...

detecting key presses on documents using javascript

I'm having trouble capturing document-level key press events on a webpage. I've tried using the following code: $(document).bind('keydown', 'a', keyevent_cb); It works fine in IE, but it's not consistent in Firefox. I&a ...

Troubleshooting Azure typescript function: Entry point for function cannot be determined

project structure: <root-directory> ├── README.md ├── dist ├── bin ├── dependencies ├── host.json ├── local.settings.json ├── node_modules ├── package-lock.json ├── package.json ├── sealwork ...

Creating a constant in an AngularJS module: The definitive guide to defining module-specific constants

Within a page, numerous Angular modules are present. I have set up a constant for each module containing the version number. var module1 = angular.module('module1').constant('version', '1.2.3'); var module2 = angular.module(& ...

Using ES6, one can filter an array of objects based on another array of values

Seeking assistance with creating a function to filter an array of objects using another array as reference values. For example: The array containing objects: const persons = [ { personId: 1, name: 'Patrick', lastName: 'Smit ...

The proper method for updating data on a backend API using Axios and Vue

I am working on a Vue application that includes several form fields. I want to ensure that any changes made by the user are saved in real-time to a backend database using a REST API with Axios, without requiring the user to click a save button. I have two ...

Assign the value to the data property once the promise has been fulfilled

When developing my app, I encountered a challenge of connecting to the MySQL backend using Sequelize. Here is the code snippet that I am currently working with: export default { data () { return { username:'' ...

"Exploring the TypeScript typing system with a focus on the typeof operator

My goal is to create a function that will return the typeof React Component, requiring it to adhere to a specific props interface. The function should return a type rather than an instance of that type. Consider the following: interface INameProps { ...

Sync Data Automatically from SQL Database

For the past two months, I've been researching how to achieve an effect similar to the auto-updating sales on the page. So far, I haven't had any luck. I do have a PHP file that counts the number of results in a database and displays them as a n ...

The integration of Vue JS is not displaying properly in an Electron application

My electron app is loading Vue JS 2 from my local machine, but when I attach my el to an element, it completely empties the element and replaces its contents with a Vue JS comment. What could be causing this issue? index.html <!DOCTYPE html> <htm ...

Verify the functionality of the input fields by examining all 6 of them

I'm facing a challenge with a validation function in my project that involves 6 input fields each with different answers. The inputs are labeled as input1 to input6 and I need to verify the answers which are: 2, 3, 2, 2, 4, and 4 respectively. For e ...