Dynamically Filter an Array by Object Properties

I am attempting to filter an array based on specific attributes, such as color and size. I understand that it can be filtered using code like this:

const products = [
  {
    name: "Product A",
    attributes: [
      {
        color: "Yellow",
        size: "Small",
        price: 100,
        quantity: 30,
      },
      ...
    ],
  },
];

const result = data.map(({ attributes }) =>
    attributes.filter(({ color }) => color === "Red")
);

console.log(result)

However, what if there are numerous attribute colors and sizes? Is there a way to separate them by their color? For example, filtering all yellow data:

[
      {
        color: "Yellow",
        size: "Small",
        price: 100,
        quantity: 30,
      },
      ...
]

Similarly, for sizes, how would I filter and return all small-sized data like this:

[{
    color: "Yellow",
    size: "Small",
    price: 100,
    quantity: 30,
  },
  ...
]

If my query is unclear, please leave a comment below so I can provide further clarification. Thank you for your assistance.

Answer №1

Even though the response doesn't exactly align with the question's structure, it proves to be quite effective.

const data = [
  {
    type: "fruit",
    category: "apple"
  },
  {
    type: "vegetable",
    category: "carrot"
  },
  {
    type: "fruit",
    category: "orange"
  }
];

function organizeDataByProperties(data, ...properties) {
  const collection = {};
  for(let i = 0; i < properties.length; i++) {
    const property = properties[i];
    collection[property] = {};
    for(let j = 0; j < data.length; j++) {
      const item = data[j];
      if(!collection[property][item[property]]) collection[property][item[property]] = [];
      collection[property][item[property]].push(item);
    }
  }
  return collection;
}

console.log(JSON.stringify(organizeDataByProperties(data, "type", "category")));

Answer №2

Easy solution using Array.filter. I hope this is the desired output format for you.

var properties = [{color:"Yellow",size:"Small",price:100,quantity:30},{color:"Yellow",size:"Medium",price:150,quantity:20},{color:"Yellow",size:"Large",price:200,quantity:10},{color:"Red",size:"Small",price:100,quantity:15},{color:"Red",size:"Medium",price:150,quantity:10},{color:"Red",size:"Large",price:200,quantity:5},{color:"Blue",size:"Small",price:100,quantity:15},{color:"Blue",size:"Medium",price:150,quantity:10},{color:"Blue",size:"Large",price:200,quantity:5}];

function filterBy(property, value)
{
    return properties.filter(item => item[property] == value);
}

console.log(filterBy("color", "Yellow"));
console.log(filterBy("size", "Large"));
console.log(filterBy("price", 200));

Answer №3

One potential enhancement involves dynamically retrieving attribute values using the following code snippet.

const colors = []
const sizes = []
const prices = []
const quantities = []

for (product of products) {
  for (attribute of product.attributes) {
    if (colors.indexOf(attribute.color) == -1) {
      colors.push(attribute.color)
    }
    if (sizes.indexOf(attribute.size) == -1) {
      sizes.push(attribute.size)
    }
    if (prices.indexOf(attribute.price) == -1) {
      prices.push(attribute.price)
    }
    if (quantities.indexOf(attribute.quantity) == -1) {
      quantities.push(attribute.quantity)
    }
  }
}

You can then retrieve values using array.filter as shown below:

for (product of products) {
  const result = product.attributes.filter(function(attributes) {
    return attributes.color == "Red"
  })
}

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

Eliminate the preset !important declarations within elements

I am currently facing a CSS conflict on my WordPress site caused by a prominent plugin. The developers of the plugin have scattered !important declarations across their style sheets, making it difficult for me as a developer to make necessary changes. Whil ...

Outputting a list of numbers from an array that were never entered by the user

Recently, I've been working on a program that takes the grades of 5 students and displays the marks that are above 70. However, I'm encountering a small issue with my code. While it successfully identifies marks over 70 like 99 and 81, it also in ...

Calculate and retrieve the result from the event handling function

I need to capture a returned value and store it in a variable within an event handler function. Below is a sample code snippet demonstrating this: var xhr = new XMLHttpRequest(); function getData(e) { if (xhr.readyState === 4) { if (xhr.s ...

Guide on constructing a lengthy data frame from a three-dimensional array for generating a facet plot displaying histograms

Currently, I am conducting simulation tests where I adjust two parameters ("x" and "y") within specific ranges, and then calculate an error score for each combination of these parameters. This simulation is repeated multiple times, and I am interested in v ...

Tips on providing validation for either " _ " or " . " (select one) in an Angular application

I need to verify the username based on the following criteria: Only accept alphanumeric characters Allow either "_" or "." (but not both) This is the code snippet I am currently using: <input type="text" class="form-control" [ ...

Having trouble with button functionality following the implementation of jquery.min.js?

We have implemented the code below, following the suggestion from this source, to replace text with icons. However, after applying the code, especially the Jquery.min.js file, the "add to cart" button on this page is no longer functioning. <script src= ...

When clicking on the file input field in Angular.js, the image name mysteriously disappears

I am currently utilizing ng-file-upload to upload images with Angular.js. The issue I'm encountering is that when a user selects a file for the second time in the same field, the name of the previously chosen image doesn't display. Below is my c ...

Is it feasible to separate the bin and lib dependencies in an npm module?

Imagine you have already successfully released a nodejs module on npm. This module is straightforward - just install and import it, provide a string and a config object, and it will return a string for you. Now, here's the twist: you want this module ...

What is the best way to toggle between tabs using a checkbox that is checked or unchecked?

I have implemented a checkbox with two sets of tabs that are meant to be displayed or hidden based on the checked state of the checkbox. Currently, the checkbox switches tabs when checked, but does not switch back when unchecked. What modifications ca ...

What are the steps for creating a grid layout with a logo header displayed at the top?

Hello everyone, I am new to using react native and I have a specific layout in mind that I would like to achieve. However, the code I currently have places the logo inside a grid. Here is the layout I am aiming for: https://i.sstatic.net/zkJcK.png impor ...

The Sequelize error message states: TypeError: an array or iterable object was expected, but instead [object Null] was received

I am encountering an issue with the findOne method from sequelize in my model. The error message I am getting states that the table referenced by the model is empty. How can I resolve this? Unhandled rejection TypeError: expecting an array or an iterable ...

Tips for efficiently storing data in the Laravel database using Ajax

I'm attempting to upload a product with multiple images to the database without refreshing the page. Despite not encountering any errors in the console, I am seeing a long block of text that starts like this: <script> Sfdump = window.Sfdump || ...

Component in Next Js fails to pass props when using getInitialProps

I am facing some challenges with Next Js and could really use some assistance. We have a component where I am utilizing "getInitialProps" to pass props to it during the server-side rendering process. However, no matter what I try, the props do not seem to ...

Convert an array into a JSON object for an API by serializing it

Currently, I am working with Angular 12 within my TS file and have encountered an array response from a file upload that looks like this- [ { "id": "7", "name": "xyz", "job": "doctor" ...

Displaying components in Vue 2 using data from an ajax call

How can components retrieved from an ajax response be rendered? For instance, suppose I have registered a component called "Test" and within the ajax response I encounter: <p>dummy paragraph</p> <test></test> <!-- vue component ...

Initiating a node request within an HTML document

I have recently started learning about node and have been practicing making http requests using the request module. In my current script, I am attempting to have a callback function execute a request that fetches HTML from a webpage and then filters it to ...

Tips on passing a float* array to a C method from a Python script when the memory allocation occurs in the C layer

I am currently attempting to invoke C methods from a Python script, where the C method in turn calls a C++ method. Within the getResults() method, I am dynamically allocating an array using malloc(). The issue arises when trying to pass arguments to float* ...

Searching for elements in JavaScript using dynamic find control

Is there a way to implement this in JavaScript using dynamic addressType? let addressType = "bar"; document.getElementById('<%= this.FindControl("'" + addressType + "'").ClientID%>').value = val; ...

Calculating information from an array using VueJS

I am eager to use VueJS to process data from my JSON source Here is an example of the data structure: JSON obtained via API [ { "id": 4, "votes": 0 }, { "id": 3, "votes": 1 }, ] In order to fetch and disp ...

Incorporate the select2 plugin into your AngularJS project for enhanced functionality

In my AngularJS application, I am utilizing the select2 plugin to showcase a list of entities (tags). This snippet shows part of my template: select.ddlTags(ui-select2="select2Options", multiple, ng-model="link.tags") option(ng-repeat="tag in tags", ...