How to verify if an object in JavaScript includes a specific value?

Obtaining an array of nested objects from a database is my current task.

Each object in the array includes a "metadataIdStrings" member that functions like a dictionary.

For instance:

    [{
  "customerId": 48,
  "uploaderId": "markdolenc",
  "filename": "1.pdf",
  "createdOn": {
    "$date": "2020-08-25T12:06:10.165Z"
  },
  "lastModified": {
    "$date": "2020-08-28T06:16:40.352Z"
  },
  ...
}]

I am tasked with filtering objects that have specific values within their "metadataIdStrings" based on a search field input.

The challenge lies in the fact that the keys in this dictionary do not remain consistent across all objects.

My initial approach was:

filteredList(){
        var searchValue = this.search;

        return this.correctDocuments.filter(doc => {
            return Object.values(doc.metadataIdStrings).some(val => {
                var includes = val.toLowerCase().includes(searchValue.toLowerCase())
                return includes
            }) 
        })
    }

However, I'm encountering issues as it does not work as expected. What could be the missing piece here?

EDIT: Upon Peter's suggestion, I delved into debugging this.correctDocuments.filter and found that it returns the correct items. The issue arose from binding data to this.search inside a table, where it searches for filenames rather than intended fields. Simple oversight on my part.

Answer №1

Perhaps these solutions could work for you.

// Extract the metadataIdStrings
const { metadataIdStrings } = response

// Transform metadataIdStrings object into an array
Object.values(metadataIdStrings).filter(value => { /* add your filtering criteria here */ })

// If you require the keys
Object.keys(metadataIdStrings).filter(key => { /* metadataIdStrings[key] === something */ })

Furthermore, it appears that the source array containing metadataIdStrings is actually a single object within an array, so make sure to reference it correctly.

Answer №2

Let's start with something straightforward yet similar to your example:

var data = [{
    "3968": "A1 Slovenija, d. d.",
    "3969": "A1 Slovenija, d. d.",
    "3970": "SI60595256",
    ...
  },
  {
    "continent": "EUR"
  },
  {something: "else"}];

I've excluded metadataIdStrings-related details for now. When you run

data.filter((item) => Object.keys(item).filter((k) => (item[k] && item[k].indexOf("EUR") >= 0)).length)

You will get the desired outcomes.

Next, let's adapt this procedure to your specific situation:

items.filter((item) => item.metadataIdStrings && Object.keys(item.metadataIdStrings).filter((k) => (item.metadataIdStrings[k] && item.metadataIdStrings[k].indexOf("EUR") >= 0)).length)

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

The error message "Uncaught TypeError: Unable to access property 'url' of an undefined object - Google Image API" appeared

I am facing an issue with generating 5 random images. The first row, from flicker, is working fine. However, the second row from Google is only returning 4 images and showing an error in the console: Uncaught TypeError: Cannot read property 'url&apos ...

"The reactivity of VueJs array of objects is not triggering properly when there is a change in

My state includes an array of objects structured like this: data() { return { users: [{id: 1, name: 'bob'}, {id: 2, name: 'bill'}] } } After modifying the data as shown below: this.users[0].name = 'Mary' The watc ...

Displaying a preloaded image on the canvas

Once again, I find myself in unfamiliar territory but faced with the task of preloading images and then displaying them on the page once all elements (including xml files etc.) are loaded. The images and references are stored in an array for later retrie ...

Encrypt JavaScript for a jade layout

I need to find a way to successfully pass a .js file to a jade template in order for it to display correctly within an ACE editor. However, I am encountering errors when attempting to render certain files that may contain regex and escaped characters. How ...

Retrieving the return value from an AJAX call in C# using asynchronous methods

When it comes to retrieving a value using Ajax on the client side, I rely on this JQuery function: $.ajax({ type: "POST", url: "/my-page.aspx/checkout", contentType: "application/json; charset=utf-8", dataType: "json", success: functio ...

Display an array comprising of other arrays

function PersonXYZ(fName, lName) { this.lastName = lName; this.firstName = fName; this.grades = []; this.grades.push([4, 67, 5]); this.grades.push([41, 63, 5]); this.grades.push([4, 67, 55]); } var person = new PersonXYZ('John', 'Doe&apos ...

P5js Image Selection Drop-down

Struggling to create a dropdown menu in p5js that showcases images. Facing issues with loading images, unlike in other sketches where the problem did not occur. Seeking a fresh perspective to resolve this error. Appreciate any assistance! let picker; let ...

An effective method for finding a key in a multi-dimensional array or object based on its value using JavaScript and/or jQuery

I have a unique object structure that resembles the following: var data = {}; data.items = { name : 'apple', price : '$1.00' }; data.products = { name : 'banana', price : '$0.50' }; data.goods = { name : 'oran ...

Query does not include both values in the array

I need help figuring out how to create an array that contains both SkillID and Description values. Right now, when I print the array, it only displays Description. How can I ensure that both SkillID and Description are included in the array? $skillresult ...

Selenium - How to pass a file path to a dynamically generated input element that is not visible in the DOM

Check out this example of HTML code: This is how you create a visible button and display the selected file: <button id="visible-btn">visible button</button> <p>selected file is: <span id="selected-file"></spa ...

Create a custom hook that encapsulates the useQuery function from tRPC and provides accurate TypeScript typings

I have integrated tRPC into a project that already has API calls, and I am looking to create a separate wrapper for the useQuery function. However, I am facing challenges in getting the TypeScript types right for this customization. My Objective This is w ...

php How to arrange a dynamic list of SQL array in a specific order

My online store is customized and built using PHP. It fetches products from specific categories stored in a MySQL database and presents them in tables for my customers. The code seems to be designed to sort the products by date added, but it's not fun ...

By simply clicking a button, you can input a value into a field without the need for the page to refresh

Can someone please help me figure out how to insert a specific value into an input field without refreshing the page? I have tried the following code but it doesn't seem to work. Basically, when I click the button, I want the value "1234567" to be aut ...

Having problems getting my fixed header to work on my datatable. What could be the

Struggling to make my data table Thead sticky? I attempted using position: fixed;, top: 0; with CSS but it only worked in Firefox, not Chrome, Edge, or Opera. Here is an excerpt of my Ajax code: "stateSave": false, "orderCellsTop&quo ...

Is there a way to utilize variables from a source XML file to establish points on an SVG polygon?

I've been struggling to figure out if it's possible to dynamically set points on an SVG polygon using variables that are defined by an XML document which is constantly changing. All I want is to set the path like this: var polygonToUse = window. ...

The clear function in the template slot of Vue multiselect is not functioning properly

I decided to incorporate the asynchronous select feature found in the documentation for my project. This feature allows me to easily remove a selected value by clicking on 'X'. Below is a snippet of the general component that I use across variou ...

What could be the reason for encountering an error when calling await on a function that has the async

In my node+ express application, I am facing an issue with a controller method that is performing an asynchronous operation. Despite declaring the method with the async modifier, it is throwing a SyntaxError: await is only valid in async functions and the ...

Troubleshooting Issue with React Router Component Displaying Blank Page

I have been working with React Router in an attempt to connect my App.js and Car.js components. I have included {this.props.children} in both components, but the connection is not functioning as expected. When I deploy my app, there is no sign of the Car.j ...

React JS's popup feature can be unreliable, as it tends to break the application frequently

I have been developing a web application that interacts with a public API and presents the retrieved data in a table format. However, I am encountering an issue where clicking the "Click to Display Hottest Planet" button sometimes results in an error. How ...

What is causing the "else" to activate in this particular if-else scenario?

I have implemented a method in Vue that toggles the darkMode variable when clicked. However, I'm facing an issue where it always triggers both the if and else parts of the method. data(){ return{ darkMode:false, } }, methods:{ darkMode ...