Step-by-step guide on filtering an array of objects using Vuejs and TypeScript

For this particular project, I am utilizing Vuejs Typescript with a data structure that looks like this:

["order":
  {
    "id":1,
    "created_at":"2019-12-06T10:22:17Z",
    "status":"open",
    "updated_at":"2020-07-27T04:21:06Z",
    "recipient":null,
    "custom_fields":[
      {"id":2,"value":'ABC'},
      {"id":3,"value":'EFG},
      {"id":4,"value":'CSA'}
    ]
  }
]

The function I use to retrieve the data is as follows:

private mapUnprinted (data: any) : IUnprintedSet {
    const result: IUnprintedSet = { orders: [], pagination: {} }
    if (data) {
      data.forEach((anUnprinted: any) => {
        const order: IUnprinted = {
          id: anUnprinted.id,
          created_at: anUnprinted.created_at,
          status: anUnprinted.status,
          updated_at: anUnprinted.updated_at,
          recipient: anUnprinted.recipient,
          custom_fields:  anUnprinted.custom_fields
          // filter((item: any) => item.custom_fields.id === '3'),
        }
        result.orders!.push(order);
      })
      result.pagination = {
        currentPage: data.pagination ? data.pagination.currentPage : undefined,
        pageSize: data.pagination ? data.pagination.pageSize : undefined,
        totalPages: data.pagination ? data.pagination.totalPages : undefined,
        totalResults: data.pagination? data.pagination.totalResults : result.orders!.length
      }
    }
    return result
  }

I included the line:

filter((item: any) => item.custom_fields.id === '3'),

However, it appears that this code snippet does not work correctly and returns an empty array. The main issue lies in my attempt to extract the value from custom_fields where the ID is equal to 3.

This is how I tried to retrieve the custom_fields:

anUnprinted.custom_fields.filter((item: any) => item.id === '3'),
"order": {
      "id": 1,
      "created_at": "2019-12-06T10:22:17Z",
      "status": "open",
      "updated_at": "2020-07-27T04:21:06Z",
      "recipient": null,
      "custom_fields": []

Answer №1

Your identification number is in numeric form, so you could try:

item.id === 3

or

item.id == '3'

Answer №2

There is a mismatch in data types - the id uses numbers while the filter function is checking for strings.

I'm still learning and open to correction to enhance my skills

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

Is there a way to dynamically shift arrow key focus onto buttons in Angular using the left and right arrow keys?

I am facing an issue where pressing the arrow keys left and right does not focus or allow me to navigate through these buttons using the arrow keys. However, when checking the keycode values, they are printed according to the key pressed. I would like to k ...

I am having trouble with updating an array in React useState. Every time I try to make changes, it keeps reverting back to the initial state. What could

My current task involves managing a state array called monthlyIncidents, which contains 12 numbers that need to be updated under certain conditions. I attempted to update the elements by copying the array, modifying the specific element, and then updating ...

Unlocking Authorization in VueJS

Currently, I have Laravel 5.4 integrated with Vue.js 2.0. Is there a way to utilize Auth::user() within a VueJS template? Here's an example... <template> <p>{{ Auth::user()->name }}</p> </template> export default {} ...

Jest testing in a Vue child component is failing due to the presence of lodash

In this specific instance of my Vue app, I have globally loaded lodash as a Vue plugin in the main.js file: import _ from "lodash" export default function install(Vue) { Vue.prototype._ = _ Vue.mixin({ computed: { _: () => ...

Utilizing formData.append in TypeScript to handle arrays

Hey there! I'm facing an issue while trying to send a form to my Profile endpoint. The problem lies in the 'user:{}' field, as I am unable to properly insert my array data into this specific field. Here is a breakdown of the fields within m ...

How to inject a regular class in Angular2 without the @Injectable decorator

angular: 2.0.0-beta.9 Can we inject a non-@Injectable class into a component? For instance, if this class originates from an external Third party library. ...

Steps for removing the console warning message: "The use of enableRowSelect has been deprecated. Instead, please utilize rowSelection."

) I have integrated React Data Grid from https://adazzle.github.io/react-data-grid/ multiple times in my application. One thing I noticed is that there is a console warning related to a prop called "enableRowSelect" which indicates whether the prop is bein ...

Exploring the capabilities of Vue.js, including the use of Vue.set()

Just starting out with Vuejs and I have a query regarding the correct approach to achieve what I want. My Objective I aim to have some dates stored in an array and be able to update them upon an event trigger. Initially, I attempted using Vue.set, which ...

Unable to pass props to component data using Vue framework

I'm facing an issue with passing props in my component to the same component's data object. For some reason, I'm only receiving null values. Does anyone have any suggestions on how I should approach this problem? It seems like my Vue compone ...

Looking to implement pagination in Vue.js - what steps should I take?

Hi there, I'm currently facing an issue while trying to paginate my data. The error message in my console reads: Property or method "$index" is not defined on the instance but referenced during render. Below is my HTML template where I display the da ...

What is the most efficient method for transferring Flask variables to Vue?

I am currently developing a visualization application using a flask server and vue.js for the front end. Other discussions on this topic explore how to avoid conflicts between vue.js and flask variable syntax, as shown here. In my scenario, I'm inte ...

Currently trapped within the confines of a Next.js 13 application directory, grappling with the implementation of a

I need to figure out how to export a variable from one component to layout.tsx in such a way that it is not exported as a function, which is currently causing the conditional check in the class name to always be true. Below is the code snippet: // File w ...

What are the steps for pairing jsplumb with vuejs?

I successfully implemented the jsPlumb script in an .html file within the script tag and it is functioning properly. <body> <div id="q-app"></div> <!-- built files will be auto injected --> <script> jsPlumb.rea ...

What is the process for establishing the initial state in Vuex 2?

Working with Vue.js 2.0 and Vuex 2.0 in a small app, I've initialized the store in the 'created' life-cycle hook on the root Vue instance by calling an action that fetches the initial state from an API. This is how it looks in my Main Compon ...

Is it possible for me to determine when all images have finished loading in order to update the isLoaded variable to true?

I am using the template below: <template> <div v-if='isLoaded'> <div @click='selectSight(index)' v-for='(sight, index) in sights'> <img :src="'https://maps.googleapis.com/maps ...

Resolve the problem in Angular 6 related to an unused type and the absence of a certain property

I recently watched a video tutorial (link: https://www.youtube.com/watch?v=z4JUm0Bq9AM) and encountered some errors in my CLI. The specific errors are as follows: ERROR in sidebar.component.ts(12,5): error TS7028: Unused label. sidebar.component.ts(14,56 ...

Validation of decimal numbers in JavaScript without the presence of any other characters

Looking to create a JavaScript regex to validate an 8-digit number that may include decimals. The current regex /^\d+$/ allows for any other characters such as ( , * $ etc. How can I modify this to only accept numbers and periods? For example, the nu ...

Strange anomalies arising in frontend Apollo and GraphQL integration

Currently, I am working with nuxt.js and apollo. One issue I am facing is that when I click a button, it sends a request to the graphql server. The strange part is that the first time I click the button, everything works as expected. However, when I clic ...

The React hook useState is struggling to accurately map array objects

Recently, I encountered an issue with a form that sends an array of objects to another React Functional Component: import React, { useState } from 'react' import uuid from 'uuid/v1'; const NewMovieForm = ( {addMovie }) => ...

Design system styled component - "The type of X cannot be explicitly defined without a reference..."

How can I resolve this TypeScript issue? I have a styled component exported from a style.ts file and used in the index.tsx file of my React component: style.ts: import { styled, Theme } from '@mui/material/styles'; type CardProps = { theme? ...