Tips on finding the right parent object by utilizing the information stored in the nested array

I have a collection of objects structured as follows:

var items = [
  {
    itemId: 0,
    itemQuantity: 10,
    attributes: [
      { type: "Size", value: "Small" },
      { type: "Color", value: "Black" }
    ]
  },
  {
    itemId: 1,
    itemQuantity: 20,
    attributes: [
      { type: "Size", value: "Small" },
      { type: "Color", value: "White" }
    ]
  },
  {
    itemId: 2,
    itemQuantity: 30,
    attributes: [
      { type: "Size", value: "Medium" },
      { type: "Color", value: "Black" }
    ]
  },
  {
    itemId: 3,
    itemQuantity: 40,
    attributes: [
      { type: "Size", value: "Medium" },
      { type: "Color", value: "White" }
    ]
  }
];

In addition, I have a simple array containing the following elements:

let selectedAttributes = ["Small", "Black"];

The objective is to retrieve the parent object based on matching values from the nested array (attributes). Specifically, I need to identify the object that contains both "Small" and "Black". The desired result should be:

let result = [
  {
    itemId: 0,
    itemQuantity: 10,
    attributes: [
      { type: "Size", value: "Small" },
      { type: "Color", value: "Black" }
    ]
  }
]

Here is the current code snippet I am using. Upon logging the result, it returns an empty array:

let result = items.filter((item, index) => {
  return item.attributes.some(attri => attri.value === selectedAttributes);
});

console.log(result);

Answer №1

Ensure that you are checking the value of each matched object, not just the first one (as seen with .some). To achieve this, utilize .includes to verify if every value attribute in each object is present in your attribute list:

const items = [ { itemId: 0, itemQuantity: 10, attributes: [ { type: "Size", value: "Small" }, { type: "Color", value: "Black" }, ] }, { itemId: 1, itemQuantity: 20, attributes: [ { type: "Size", value: "Small" }, { type: "Color", value: "White" } ] }, { itemId: 2, itemQuantity: 30, attributes: [ { type: "Size", value: "Medium" }, { type: "Color", value: "Black" } ] }, { itemId: 3, itemQuantity: 40, attributes: [ { type: "Size", value: "Medium" }, { type: "Color", value: "White" } ] } ];

const selectedAttributes = ["Small", "Black"];
const res = items.filter((item, index) => {
  return item.attributes.every(attri => selectedAttributes.includes(attri.value));
});

console.log(res);

If your goal is to retrieve a single object rather than an array of objects, consider using .find() instead of filter(). By using .find(), the iteration stops when the inner function returns true:

const items = [ { itemId: 0, itemQuantity: 10, attributes: [ { type: "Size", value: "Small" }, { type: "Color", value: "Black" }, ] }, { itemId: 1, itemQuantity: 20, attributes: [ { type: "Size", value: "Small" }, { type: "Color", value: "White" } ] }, { itemId: 2, itemQuantity: 30, attributes: [ { type: "Size", value: "Medium" }, { type: "Color", value: "Black" } ] }, { itemId: 3, itemQuantity: 40, attributes: [ { type: "Size", value: "Medium" }, { type: "Color", value: "White" } ] } ];

const selectedAttributes = ["Small", "Black"];
const res = items.find((item, index) => {
  return item.attributes.every(attri => selectedAttributes.includes(attri.value));
});

console.log(res);


Note that the aforementioned solution assumes all attribute objects match the provided attributes. If you want to allow object attributes to include additional ones besides those in the list, utilize .every on the attribute list instead of the object attributes like so:

const items = [ { itemId: 0, itemQuantity: 10, attributes: [ { type: "Size", value: "Small" }, { type: "Color", value: "Black" }, ] }, { itemId: 1, itemQuantity: 20, attributes: [ { type: "Size", value: "Small" }, { type: "Color", value: "White" } ] }, { itemId: 2, itemQuantity: 30, attributes: [ { type: "Size", value: "Medium" }, { type: "Color", value: "Black" } ] }, { itemId: 3, itemQuantity: 40, attributes: [ { type: "Size", value: "Medium" }, { type: "Color", value: "White" } ] } ];

const attrs = ["Small", "Black"];
const res = items.filter((item, index) => {
const values = item.attrs.map(o => o.value);
  return attrs.every(attri => values.includes(attri));
});

console.log(res);

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 express app.get middleware seems to be malfunctioning due to a 'SyntaxError: Unexpected end of input'

Currently, I'm diving into an Express tutorial on YouTube but hit a roadblock with middleware that has left me bewildered. In my primary file, the code looks like this: const express = require('express'); const path = require('path&ap ...

Retrieving a value using forEach in protractor - Dealing with closures

I am facing an issue with the helper code below, as it is not returning the correct number of occurrences of a string. this.getActualFilteredStatusCount = function(strFilter){ return this.getTotalRows().then(function(count){ var totalCount = ...

How to pass a JSON object to a component's constructor in Angular 2

In a unique situation, my primary component config.editor.component performs extensive processing and generates various JSON objects. I am content with this approach. The template for this component then proceeds to render another component - api.entry.com ...

The loading time for the Ajax request is unreasonably slow

I am currently managing a website dedicated to League of Legends. My main task involves requesting statistics from the Riot Games API based on a player's name, which returns the information in JSON format. However, there is a significant delay in load ...

Retrieve the data in the format of [1,2,3] from a MySQL database by employing PHP and jQuery

I'm currently working on a jQuery code that connects to getdata.php. The val in this code is a dynamic value and the function gets called every time an option is selected from a dropdown. function getMoleculeData(val){ var molval=val; ...

Trouble with minification in Sencha cmd 5

I've been attempting to compress a Sencha 5 project using Sencha CMD, but I keep experiencing failures. sencha generate app -ext demoApp ./demoApp Then, in an effort to compress the application, I entered the following command: sencha app build ...

What is the proper way to reference an EJS function that is declared in a different EJS file?

document 1: jsfunction.ejs <% function testFunction() {return 42;} %> file 2: data.ejs <% include jsfunction.ejs %> <% testFunction(); %> result: ReferenceError: 1| <% include jsfunction.ejs %> >> 2| <% testFuncti ...

What are some strategies for establishing communication between sibling components in Vue?

Currently, my Vue app has a structure that includes a "blackout" component for displaying modals and a router-view for various sub-menus. These components are siblings at the same level. <blackout v-if="this.popup.currentPopup"></blacko ...

Development versions of npm libraries

Lately, I came across a library called react-3d-components that offers some d3 react components with basic charts. It's an impressive collection of components. However, when trying to access the source code due to incomplete documentation, I found my ...

Combining multiple conditions with Sequelize in a JOIN statement

Currently, I am attempting to execute a query using Sequelize ORM with a custom join condition. For example: User.findAll({include: [{model: Post, where: {active: true}}] Here is the result of the join condition: INNER JOIN `posts` AS `post` ON `users`.` ...

Creating a cohesive display of an array in HTML with printing operations

I have three arrays that display nicely in HTML format from search engines. Here are the foreach loops to print them out: Bing API foreach($jsonObj->d->results as $value){ echo "<a href=\"{$value->Url}\">{$value-> ...

Tips for effortlessly enlarging an element

When you click on "#sidebarnav>li", the following happens: 1) The second child of it - <ul> element will expand and its class toggles between "collapse" and "collapse in". 2) "#sidebarnav>li" will receive the "active" class. 3) The "aria-ex ...

In React, when pushing to an array, it is the index that gets returned instead of the items

I'm currently working on incorporating a new object into an array that I'm fetching dynamically through my API. Users fill out a form, and the data is transmitted from the form to the state. The initial fetch stores the original array in a React ...

When I attempted to POST a js::array in JSON, the response returned "undefined:undefined"

I have a javascript array on the frontend that I need to send to my Tomcat server. Currently, I am using the following code but encountering issues: console.log("preview list. postUsers()"); console.log(Ext.getCmp("preview-container").get ...

"Let's delve into the world of dynamic variables and Javascript once

As a newcomer to JS, I've scoured countless posts for solutions, but nothing seems to work for me. The issue arises when trying to abstract the code to handle all variables rather than just explicitly expressed values. I am open to alternative method ...

Updating a database with a loop of React Material UI toggle switches

I am trying to implement a material UI switch feature that can update the Active and De-Active status of users in the database directly from the Admin Panel. Currently, the database updates are functioning correctly when toggling the switches. However, th ...

Creating multiple instances of an object

When using Javascript, I am trying to create an object in the following way: var testObject = { value: "this is my initial value", setup: function() { value: "foo" } }; Now, my goal is to instantiate this object and have different val ...

Display the input in the text box before making a selection from the dropdown menu

Latest Technologies: $(document).ready(function(){ $('#userID').change(function(){ $('#username').val($('#userID option:selected').data('username')); }); }); Coding in HTML: <select class="form- ...

Looping through multiple answers with Python

Assistance is requested to enhance the 'else' section by adding a loop that will re-ask the question if not understood. Below is the code snippet: answer = raw_input("What are your thoughts on this piece of software?") if answer == &ap ...

Using PHP's for loop to iterate through data and store them into arrays

Attempting to transmit data from JavaScript to a PHP file through an AJAX request, and then store each result in an array using PHP. queryData={"data":{"data_string":{"data":"medicine","default_field":"Content"}}} testArgument=0; $.ajax({ url:"test/q ...