Leverage a dictionary to refine and organize JavaScript data objects

If I have a specific filter set up like this:

filter = [ {key: "pl", value: 3}, {key: "sh", value: 2} ]

I am looking to use this filter to search through the following JavaScript object:

var data = [
{title: "The Uncertainty of the Poet ",
pl: 3,
si: 2,
va: 3,
te: 0,
co: 0,
or: 4,
sh: 2,
po: 0,
li: 0,
ar: 5
},
{
title: "Direction",
pl: 4,
si: 3,
va: 1,
te: 3,
co: 0,
or: 3,
sh: 2,
po: 0,
li: 0,
ar: 5
}
...
]

I attempted the following code but it did not work as expected:

var result = data.filter(function(d){
            for (item in filter) {
                return d.key==d.value;
            }

Answer №1

Here's an alternative method to verify if the object satisfies all requirements:

data.filter(function(obj) {
    return filter.reduce(function(a, f) {
        return a && (obj[f.key] === f.value);
    }, true);
});

This approach eliminates the need to check for hasOwnProperty due to the implementation of reduce. To verify if any of the filter conditions are met, you can modify it as follows:

data.filter(function(obj) {
    return filter.reduce(function(a, f) {
        return a || (obj[f.key] === f.value);
    }, false);
});

Answer №2

You may also accomplish this in the following manner:

let filters = [{key: "pl", value: 3}, {key: "sh", value: 2}]

let data = [
    {
        title: "The Mystery of the Poet ",
        pl: 2,
        si: 2,
        va: 3,
        te: 0,
        co: 0,
        or: 4,
        sh: 3,
        po: 0,
        li: 0,
        ar: 5
    },
    {
        title: "Path",
        pl: 3,
        si: 3,
        va: 1,
        te: 3,
        co: 0,
        or: 3,
        sh: 2,
        po: 0,
        li: 0,
        ar: 5
    }
]

let result = data.filter((item) => {
  for(let i = 0; i < filters.length; ++i) {
    let filter = filters[i];

    if(item[filter.key] && item[filter.key] === filter.value) {
      return true;
    }
  }

  return false;
});

Answer №3

If you're looking to match either of the specified values, this solution should do the trick:

criteria = [ {key: "pl", value: 3}, {key: "sh", value: 2} ]

var result = data.filter(function(item) {
    return item.pl === criteria[0]['value'] || item.sh === criteria[1]['value']
})

To prevent any confusion, I've renamed the array as criteria.

Answer №4

To enhance your for in loop, you need to delve deeper into working with each individual object within the array.

Consider utilizing Array#every() to ensure that every object in the filter array corresponds to a match in the data object.

// Filtering main data
var result = data.filter(function(dataObj){
   // Verify if all properties within the filter array have a matching value
   return filter.every(function(filterObj){
      // Compare the value of property found in filterObject with corresponding value 
      return dataObj[filterObj.key] === filterObj.value
   })
})

console.log(result)
<script>
var filter = [ {key: "pl", value: 2}, {key: "sh", value: 3} ]

var data = [{
    title: "The Uncertainty of the Poet ",
    pl: 2,
    si: 2,
    va: 3,
    te: 0,
    co: 0,
    or: 4,
    sh: 3,
    po: 0,
    li: 0,
    ar: 5
  },
  {
    title: "Direction",
    pl: 4,
    si: 3,
    va: 1,
    te: 3,
    co: 0,
    or: 3,
    sh: 2,
    po: 0,
    li: 0,
    ar: 5
  }
 
]
</script>

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 Serialization problem in next.js when using getStaticProps

While working on my project with next.js, I encountered an issue where the axios fetch in getStaticProps wasn't functioning properly even though the URL was serialized in the configuration. I attempted to serialize it again by passing the response to ...

Retrieve the string value from a JSON object beginning at a designated position

Trying to figure out how to extract a specific value from a JSON object. Here's the JSON example: { "posts":{ "fields":{ "date":"2015/01/24", "date_end":"2015/01/25", "time":"23:00 - 05:00" } } } I need to store the 05:00 part ...

JavaScript Sort function malfunctioning and not correctly sorting

I am having trouble sorting div elements by price values. The code seems to be working fine, but the sorting of numbers doesn't appear to be completely accurate. For example, in my jsfiddle, when the button is clicked, the number 21.35 is displayed a ...

Node JS fails to return body content in POST request

Exploring Node JS for the first time and attempting to post data to a specific URL and retrieve it. Using Postman for this task, but encountering an issue where the response data is coming back as undefined despite receiving a 200 status code. Even after ...

Adding a Table Row in jQuery without Appending it to the Bottom of the Table

I am working on a project that involves an HTML Table where the user can add a new Row by clicking a button. However, I want the new Row to be added not at the end of the table, but after the last row of input fields. To demonstrate, I have prepared a sam ...

Importing JavaScript files to work with Vue-Router: A Step-by-Step Guide

Seeking guidance on importing JavaScript files correctly throughout my Vue project, including within the components used to implement changes with Vue-Router. Currently, encountering an issue where I must reload the component in order for the JavaScript to ...

The DiscordAPIError occurred due to the incorrect placement of required options in the form body. In order to resolve this issue, ensure that required

Hey everyone! So, I've been trying to solve an issue I encountered after posting my initial question without receiving any answers. I've searched extensively online, formatted the code, but unfortunately, I still haven't been able to find a ...

Creating a function that writes to a file by utilizing the data input from

After running the provided code snippet, it successfully works in a standalone project. However, I am interested in making modifications to replace the variable "sample_text" with an output that is displayed in the terminal instead of being hardcoded int ...

Duplicate the Date object without retaining previous data

Struggling with creating a custom deep clone feature that's encountering issues with the Date object. For instance, let now = {time: new Date()} or let now = {data: new Date().getDay()}. When attempting to copy it, the goal is not to replicate the cur ...

Why is jQuery button function only functioning for the first button?

I'm encountering an issue with my table of records. Each row in the table has a submit button that triggers an AJAX request to the server when clicked. Strangely, the first button works perfectly and sends the request as expected. However, subsequent ...

Is it possible to retrieve duplicate objects within the same array?

My array contains multiple objects. arr = [ {name: 'xyz', age: 13, }, {name: 'abc', age: 15, }, {name: 'abc', age: 15, }] I am seeking a solution to identify and remove duplicates in this array. Is it possible to achieve th ...

JavaScript is reporting that the length of the array is not defined, rather than the array itself

My goal is to utilize data from the Politifact API by saving it in an array named "superArray." I achieve this by making three API calls and adding 10 values from each response to superArray, as shown below: const URL1 = "https://www.politifa ...

Error connecting to the network: apisauce

Encountered a NETWORK_ERROR while attempting to fetch data from my Django server. CORS headers are functioning correctly on the backend. I have tried using localhost and my machine's IP address, but it still does not work. Here is the result of con ...

When trying to pass 3 parameters from an Angular frontend to a C# MVC backend, I noticed that the server side was receiving null

I have encountered an issue where I am attempting to pass 3 parameters (2 types and one string) but they are showing up as null on the server side. Below is my service: const httpOptions = { headers: new HttpHeaders({ 'Content-Type&ap ...

Tips for utilizing Vue 'component' with just Vue added as a page add-on using <script>:

I am trying to incorporate a Vue component called vue-timeago: import VueTimeago from 'vue-timeago' Vue.use(VueTimeago, { name: 'Timeago', // Component name, `Timeago` by default locale: undefined, // Default locale locales: { ...

Tips for creating a validation section in a CRUD application using React.js

I have been working on developing a CRUD app using ReactJS. However, I am facing some challenges with the validation process as it does not seem to be working correctly and I am not receiving any results. As a beginner in this field, I would greatly apprec ...

The output of JSTree's data.rslt.obj.text() function is an array of text values, not just the text from the specified node

I am facing an issue with the jstree where it is returning a concatenated list of node names when I try to rename a node, instead of just the text for the node I am renaming. The jstree is set up to load on demand. How can I ensure that only the text for ...

Leveraging the Meteor Framework for Application Monitoring

Exploring the potential of utilizing Meteor Framework in a Monitoring Application. Scenario: A Java Application operating within a cluster produces data, which is then visualized by a Web Application (charts, etc.) Currently, this process involves using ...

Different ways to notify a React/Next.js page that Dark Mode has been switched?

I am in the process of creating my first basic Next.js and Tailwind app. The app includes a fixed header and a sidebar with a button to toggle between dark and light modes. To achieve this, I'm utilizing next-theme along with Tailwind, which has been ...