Filtering an array of objects within another array in Javascript based on specific criteria

Here is an array example :

exampleArray = [
{
  category: 'Fruits', items: [
  { id: 1, name: 'Apple', selected: true },
  { id: 2, name: 'Banana', selected: false },
  { id: 3, name: 'Orange', selected: true }
  ]
},
{
  category: 'Colors', items:
    [
      { id: 0, name: 'Red', selected: true },
      { id: 1, name: 'Blue', selected: false },
      { id: 2, name: 'Green', selected: true },
      { id: 3, name: 'Yellow', selected: false }
    ]
}

];

I am trying to filter out only the elements with "selected" set to true.

This is what I have tried:

const filteredItems = exampleArray.filter((category) => {
    return category.items.filter( item => item.selected === true)
  })

However, it currently returns all elements regardless of selection status. Any advice would be appreciated!

Thank you.

Answer №1

To enhance the functionality, it is recommended to retrieve the complete object with a condition applied to the items array rather than filtering only defaultColumnsWithItems.

In this particular situation, the map function is employed to yield our object. For the items array, the filter function sieves out the selected item in each element.

const defaultColumnsWithItems = [
    {
      column: 'Contrie', items: [
      { id: 1, label: 'USA', selectedItem: true },
      { id: 2, label: 'FRANCE', selectedItem: false  },
      { id: 2, label: 'MAROC', selectedItem: false  }
      ]
    },
    {
      column: 'Categorie', items:
        [
          { id: 0, label: 'Alimentaion', selectedItem: true },
          { id: 1, label: 'ricolage', selectedItem: false },
          { id: 2, label: 'Literie', selectedItem: true },
          { id: 3, label: 'Menage', selectedItem: false },
        ]
    }
]
const items = defaultColumnsWithItems.map(el => {
    return {
        column: el.column,
        items: el.items.filter(i => i.selectedItem)
    }
})
console.log('items: ', items);

Answer №2

Give this a shot

transformedColumns.map(function(result) {
  result.items = result.items.filter(item => item.selected);
  return result;
});

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

How do I access the previous and current values in a v-for loop in Vue.js in order to compare them?

I am working on a structural component that involves looping through a list and performing certain actions based on the items: .... <template v-for="(item, INDEX) in someList"> <template v-if="thisIsArrayList(item)"> ...

Upon the creation of a new Post and attempting to make edits, the field is found to be blank

<template> <div class="card m-3"> <div class="card-body"> <Form method="post" @submit="submitData" :validation-schema="schema" ref="myForm" v-slot="{ errors, ...

Tips for live streaming a canvas element using WebRTC

While researching about WebRtc, I stumbled upon this amazing project on GitHub: https://github.com/mexx91/basicVideoRTC I have successfully tested the communication between 2 cameras using node.js. Is it possible to capture a stream from getUserMedia, m ...

What is the process of passing a function into a custom react context provider that allows for state editing?

Below is the code snippet I am currently working with: import React, { useState } from 'react' export const NumberContext = React.createContext() export function NumberProvider({ children }) { const [numbers, setNumbers] = useState([]) fu ...

Angular - Unable to locate pipe with specified name

I ran the "ng g pipe" command to create a custom pipe. However, I encountered a console error when trying to use it in my code. Please see the screenshots attached below for reference: Error: error NG8004: No pipe found with name 'filterByPrcName&apos ...

Tips for effectively testing an Angular directive

I'm having trouble testing an Angular directive due to encountering the following unexpected error: Error: Unexpected request: GET /api/players/info It seems that the issue may stem from references to my controller within the directive definition ob ...

Validation for prototype malfunctioning

I am currently using Prototype.js to implement form validation on my website. One of the fields requires an ajax request to a PHP file for validation purposes. The PHP file will return '1' if the value is valid and '0' if it is not. Des ...

Experiencing delays with Angular 4 CLI's speed when running ng serve and making updates

After running ng serve, I noticed that the load time is at 34946 ms, which seems pretty slow and is impacting our team's performance. Additionally, when we update our code, it takes too long to reload the page. https://i.sstatic.net/lpTrr.png My Ang ...

Descending order of index numbers

I have a table with indexing numbers and when I add a new row, I want the current value to be displayed in the top index number 2. However, my current code is displaying it as 0,1,2 instead of 2,1,0. Here is my HTML file: <mat-table #table [dataSource ...

Cease the loading of a script in an HTML file

I have encountered a challenge in preventing a script from loading on my Wordpress website. The HTML file contains two scripts: <script type="0f1a6d7ca503db410c0d10c4-text/javascript" src='https://www.[-----------].se/wp-content/plugins/ ...

Having trouble selecting checkboxes in React Native

When working on React Native tests, I utilize react-native-paper. Below is the code snippet: {(!props.question.isSingleAnswer && props.question.answers.length) && <View> {props.question.answers.map((item) => ( ...

The module in Node.js is unable to be loaded

Dealing with a common problem here. Despite trying to reinstall npm, deleting node_modules files and package-lock.json, the issue persists. The console output is as follows: node:internal/modules/cjs/loader:1080 throw err; ^ Error: Cannot find module &apo ...

Having trouble getting the Bootstrap modal form to submit when using Knockout's submit binding?

Check out my jsFiddle example by clicking here. I am currently working on a form within a bootstrap modal. The problem I'm facing is that the knockout submit binding doesn't get executed unless the user clicks on the submit input. It seems like ...

Exploring the capabilities of useRef in executing a function on a dynamically created element within a React/Remix/Prisma environment

I've been trying to implement multiple useRef and useEffect instructions, but I'm facing difficulties in getting them to work together in this scenario. The code structure involves: Remix/React, fetching data from a database, displaying the data ...

Tips for managing Uncaught (in promise) DOMException: An interruption in the play() request due to a pause() call

My code in the aspx page allows for playing audio files of wav format within the browser. However, I have encountered an issue where wav audios are not playing in Chrome browser, while they work in Firefox. How can I address this exception? <script&g ...

Warning message appears while scraping

I have been using selenium for web scraping on the following website: My code functions properly by navigating through pages and extracting table data until I encounter a warning message: DataTables warning: table id=table-example - Invalid JSON respon ...

Utilizing Struts2, jQuery, and `document.getElementById` to retrieve undefined values from form fields in JavaScript

When I submit this form, I am encountering undefined values in the browser console. Have I made a mistake in the code somewhere? Oddly enough, I receive correct values when submitting other forms within the same project. Here is the exact error image: $( ...

Navigating a JSON object in d3 after it has been loaded

After loading a JSON object using d3.json and assigning it to a global variable, I encountered an issue where the console returned 'undefined' when printing the global variable. However, typing the global variable in the Chrome console returned t ...

How can I implement a loop using .then in JavaScript?

Looking to understand the .then concept in JavaScript, I am curious if it is feasible to generate a series of .then's using a for loop. request.send(myRequest) .then(r => console.log(r, 0)) .then(r => console.log(r, 1)) .then(r => ...

Issue encountered: "An error has occurred stating that your cache folder contains files owned by root. This is likely a result of a bug present in older versions of npm. This issue arose during the execution of the

While attempting to create a new react app using the command npx create-react-app example_app, I encountered the following issue: [ Your cache folder contains root-owned files, due to a bug in previous versions of npm which has since been addressed sudo ...