Identify and sort JSON objects based on keys with multiple values

My JSON file contains objects structured like this:

[
    {
        "name" : "something",
        "brand": "x",
        "category" : "cars"
    },
    {
        "name" : "something2",
        "brand": ["x", "y"],
        "category" : "bikes",
    }
]

When filtering by category, my function works fine. Here's how it looks:

filterObjects(key, value) {
    if (key == 'category') {
        return objects.filter(item => item.category == value);
    }
}

However, when I try to filter by brand, only the first item is returned. How can I adjust my filter function to loop over each value and return all matching items?

Answer №1

Before applying any filter, it is important to determine if the field contains an array value:

const customFilter = (property, targetValue) => {
  return data.filter(object => {
    // Accessing a field of the object in a different way.
    const propertyValue = object[property];

    // Check if the field is an array
    if (Array.isArray(propertyValue)) {
      
      // If it's an array, we need to check if it includes the target value
      return propertyValue.includes(targetValue);

    // If not an array, compare directly with the target value
    // Using === for strict comparison over == for loose comparison
    } else {
      return propertyValue === targetValue;
    }
  });
};

Answer №2

It seems like you're looking to filter objects based on a specific key/value pair. Here's a function that can help with that:

// Filtering objects by key and value:
function findObjectsByKeyValue( key, value ) {
    var result = [];
    objects.forEach( function(object) {
        if ( object[key] == value ) {
            result.push( object );
        }
    })

    return result;
}

let filteredObjects = findObjectsByKeyValue( 'type', 'cars' );

Answer №3

My assumption is that you are attempting to achieve the following condition where value === "x":

filterObjects(key, value) {
    if (key == 'brand') {
        objects.filter(item => item.brand == value);
    }
}

When evaluating the check for the first element (element [0]), your item.brand === value comparison becomes "x" == "x", which is true and therefore passes. However, for the second element (element [1]), it turns into

["x", "y"] == "x"
, leading to a false result.

You might want to create a comparison function that returns true when two values are equal or when the first value is an array that includes the second one. Then, use this custom function instead of the == operator for your comparison.

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

Update the parameter value in a URL using JavaScript

I have a URL similar to this one here. something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false The parameter I'm interested in is showHiddenElements, and I would ...

What are the implications of AngularJS's filter on performance?

I came across an interesting article on optimizing ng-repeat in AngularJS that discussed the following: An AngularJS filter in your HTML will run multiple times during every digest cycle, even if there have been no changes in the data or conditions. Thi ...

Transferring data from JavaScript to ASP.NET (via AJAX)

I'm trying to figure out how to pass variables from JavaScript to a textbox. I have a variable in JavaScript but I am unsure how to transfer it to the textbox. I have heard that using AJAX makes it easy, but I don't know how to implement it. I th ...

How can I transfer a value from one form to another using AngularJS?

Trying to retrieve the Id from a table and pass it to a controller, however, I am facing an issue where the Id value is lost every time the form changes. Is there a better way to handle this? Below is the service and controller code: //Retrieving IdValue ...

Utilizing Ajax looping to generate dynamic HTML content with Bootstrap tabs

I am looking for a way to fetch multiple JSON files and display the data from each file in separate Bootstrap 3 Tabs. I understand that the getJSON function does not wait for completion before moving on, but I need help with using callbacks in situations ...

The post function is causing an issue and displaying an error

I am currently working on a test application that is based on the tutorial found at https://docs.angularjs.org/tutorial/step_00. The app is functioning well, however, I am encountering an issue with the post method. index.html ... <div class="control_ ...

Module or its corresponding type declarations not found in the specified location.ts(2307)

After creating my own npm package at https://www.npmjs.com/package/leon-theme?activeTab=code, I proceeded to set up a basic create-react-app project at https://github.com/leongaban/test-project. In the src/index.tsx file of my react app, I attempted to im ...

Scrolling through a list in Angular using cdk-virtual-scroll-viewport while selecting items via keyboard input

Looking to implement a customized Autocomplete feature. As the user begins typing, a small window should appear with selectable options. I want users to have the ability to navigate and select an option using their keyboard. For instance: - User types "H ...

Navigating the elements within R Shiny: A comprehensive guide

Can anyone help me figure out how to access specific elements in my Shiny app using their HTML tags? In this particular example, I need to retrieve all h1 elements along with their respective labels and IDs. library(shiny) ui <- fluidPage( h1("Get" ...

Leveraging JSON in Play 2

Currently, I am working on developing a straightforward application that allows me to manage different users by creating, reading, updating, and deleting their information. Initially, I set up a basic UI-based view, controller, and model which are function ...

Can asynchronous programming lead to memory leakage?

I'm wondering about the potential for memory leaks in asynchronous operations, specifically within Javascript used on both frontend and backend (node.js). When the execute operation is initiated, a delegate named IResponder is instantiated. This dele ...

"Bringing in" ES6 for Node

I am interested in utilizing import from ES6 instead of require from common.js in Node. Surprisingly, I initially assumed that import would function automatically in Node. However, it appears that it does not. Is there a specific npm package that needs t ...

Promise-based React Redux Login: An error occurred during login process

I'm currently working on my first React+Redux application and I'm still in the scaffolding phase. As a newcomer to React, I've encountered an issue with my simple login app. The AuthAction returns a Promise from the login(username, password) ...

Ways to resolve the error message "TypeError: 'setOption' is not a function on type 'MutableRefObject' in React"

CODE export default function EChart({ option, config, resize }) { let chart = useRef(null) let [chartEl, setChartEl] = useState(chart) useEffect(() => { if (resize) { chartEl.resize() } if (!chartEl.cu ...

Simple steps for calling a lit component in React using the ScopedElementsMixin:1. Import

Looking to incorporate the web component Button (lit) into my project using a similar tag approach. For instance, if the <button-test> tag is present on the website, then it should be converted to <button-test-12345>. This is why ScopedElements ...

Updating parent components through child components in ReactWould you like another unique

In my current project, I am attempting to change the state of the main component labeled App.tsx by using a child component called RemarksView.tsx. I have attempted passing props such as setRemarks and remarks, but unfortunately the state in the parent c ...

Create a basic cache within an AngularJS service to store data retrieved from HTTP requests, ensuring that the cache returns an object

Looking to implement a simple caching mechanism in an AngularJS service for data retrieved from HTTP requests. The goal is to always reference the same object to avoid duplicating requests. Below is an example code snippet showcasing the issue at hand. Li ...

Send function arguments to populate dropdown menus with JSON data

Is there a way to pass the parameter into "foodName" from the function that sends the url and id, without explicitly mentioning it in the function? For example, could you create a more generic function like: call('/url/to/foodlist', "foodLis ...

Removing leading zeros from numeric strings in JSON data

I am facing an issue with my jQuery-based JavaScript code that is making an Ajax call to a PHP function. updatemarkers.xhr = $.post( ih.url("/AjaxSearch/map_markers/"), params).done( function(json) { <stuff> } The PHP function returns the follo ...

JavaScript Plugins for Cordova

The more I delve into the inner workings of Cordova, the clearer it becomes to me. Yet, one area that continues to perplex me is the structure of JavaScript plugins. Typically, I write my JavaScript code as follows, adhering to what I believe is the stand ...