Eliminate an array from another array if a specific value is present in an object

I've been struggling with removing an entire array if it contains an object with a certain value within. I've searched high and low, but haven't been able to find a solution that fits my specific problem.

In my data structure, I have arrays of objects which are wrapped by another array. It looks something like this:

"products": [
    [
        {
            "product.name": "A",
            "remark.name": "Good"
        },
        {
            "product.name": "B",
            "remark.name": "Good"
        }
    ],
    [
        {
            "product.name": "A",
            "remark.name": "Bad"
        },
        {
            "product.name": "B",
            "remark.name": "Good"
        }
    ]
]

Desired Outcome

I want to exclude any array that contains an object with at least remark.name === Bad. The final result should look like this.

"products": [
    [
        {
            "product.name": "A",
            "remark.name": "Good"
        },
        {
            "product.name": "B",
            "remark.name": "Good"
        }
    ]
]

Attempted Solution

I tried the following code snippet:

let result = [];
products.map((product) => {
    var res = _.remove(product, function (n) {
        return n["remark.name"] === "Fail";
    });

    result.push(res);
});

This produced the following result:

"products": [
    [
        {
            "product.name": "A",
            "remark.name": "Good"
        },
        {
            "product.name": "B",
            "remark.name": "Good"
        }
    ],
    [
        {
            "product.name": "B",
            "remark.name": "Good"
        }
    ]
]

Answer №1

When filtering arrays in JavaScript, consider using Array#filter method along with Array#every. The goal is to filter out elements where the 'remark.name' property is not equal to 'Bad'.

Please note: To access properties like 'remark.name' with dots in their names, use single or double quotes appropriately.

let products = [
    [
        {
            "product.name": "A",
            "remark.name": "Good"
        },
        {
            "product.name": "B",
            "remark.name": "Good"
        }
    ],
    [
        {
            "product.name": "A",
            "remark.name": "Bad"
        },
        {
            "product.name": "B",
            "remark.name": "Good"
        }
    ]
];

let filtered = products.filter(arr => arr.every(obj => obj['remark.name'] !== 'Bad'));
console.log(filtered);

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

Deliver search findings that are determined by matching criteria, rather than by identification numbers

I am seeking to return a JSON match upon form submission, rather than simply searching for a specific ID. However, I am uncertain about how to structure this. I have the ability to search for the necessary match in a JavaScript document within one of my n ...

angular click triggers the following content

How can I make the following content appear when clicked? I have a list of content that displays up to 20 items, but I want to show the rest when clicked. I have created the nextMovieList method for this purpose. import { Component, OnInit } from ' ...

Create exclusive combinations by utilizing various arrays or vectors

I have a large number of text files, each containing lines of integer values: 17,1,2,3,4,5,6,7,10,11,12,13,15,16,20,22,24,26,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, 16,1,2,3,4,5,6,7,8,9,10,11,12,16,17,21,26,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, 23,4,5,6,7,8,9,10,12,13 ...

The administrator user assigns a user value in the authentication context, but that value remains hidden from the component where it was originally set

The authentication feature: import React, { useState } from 'react'; let selectedUserByAdmin = ''; const AuthContext = React.createContext({ setSelectedUserByAdmin: () => {}, selectedUserByAdmin, }); export const AuthContextPro ...

Mastering Vuex: effectively managing intricate data structures and dynamic state transformations

Let's say I'm utilizing an external API that interacts with Machine objects. With the API, you can create a Machine using createMachine, resulting in a complex object with various nested properties and functions to modify its state. The API inclu ...

The Redux store has been modified, yet the changes are not reflected in the

In my Posts.js component, I am mapping every object in the posts array. Within this function, I attempt to filter all notes that have the same post_id as the id of the current mapped post object and store them in a variable called filteredNotes. I then pas ...

Can existing servers support server side rendering?

I am currently working on building a Single Page Application (SPA) using the latest Angular framework. The SPA will involve a combination of static HTML pages, server side rendering, and possibly Nunjucks templating engine. My dilemma lies in the fact th ...

Transferring a zipped file between a Node.js server and a Node.js client

I am facing an issue with sending a zip file from a node.js server to a node.js client. The problem is that when I try to save the zip file, it becomes corrupted and cannot be opened. To create and send the zip file to the client, I am using the adm-zip l ...

How to monitor and respond to HTML modifications in a child component from a parent component in Angular framework

In the setup I have, there is a main component known as @Component({ selector: 'parent-comp' template: '<child-comp [inputData]="responseData"></child-comp> }) export class ChildComponent { public responseData: any; ...

Enhance your Rails 5 application with a dynamic live search feature powered by Keyup. Say goodbye to

Currently, I have a Rails 5.1.3 application with a simple contact model that stores names and phone numbers. To enable searching within the index view/page, I am utilizing Ransack. A keyup event listener written in Coffeescript captures user input as they ...

Why do identical elements show different scrollHeights when overflowed and how can this discrepancy be resolved?

I am using a plugin that generates a <p> element and continuously fills it with the content from a <textarea>. This plugin positions the <p> directly below the <textarea>, and styles them so that they appear identical in terms of th ...

The Vue component appears to be missing from the HTML code

I recently began learning Vue.js in school, and for my first assignment I need to print a h2 from a Vue component. However, I am having trouble getting it to work. Below is the code for the Vue component that I have created. var app = new Vue({ ...

The Unicode range [uXXXX] in Regex is not recognized during the AJAX request

I am currently facing an issue with removing control characters (e.g. \u0005) from the ajax response string. I have implemented a regular expression for this purpose: msg = msg.replace(/[\x00-\x1F\x7F-\x9F]/g, ''); Inter ...

The conundrum with JQuery: My script refuses to run when a variable is defined

<script> $(document).foundation( let total = 1 $("button.test").click(function(){ if ($("p.change-me").text() === "OFF") { $("p.change-me").text("ON") total = total + 1 } ...

What are the steps for setting up API REST calls proxy for a frontend hosted on Netlify?

While testing locally, I am able to successfully post a call and access it through Netlify. However, once I host the frontend app on Netlify, the POST Proxy is being set to the Netlify URL. The hosted URL: Upon clicking "Sign Up" and then clicking on "Si ...

Unable to focus on the same DOM element multiple times - Vue.js

Apologies for any syntax errors, although the code is functioning perfectly. There may have been a mistake during the copying process. Situation: I am facing an issue with a component called 'dropdown', which is repeated three times using v-for= ...

Trigger the datepicker's onselect event programmatically

Does anyone know how to manually trigger the onselect event of a datepicker? My code is currently functioning correctly (retrieving data from a database based on the value of the datepicker's altfield), but I'm having an issue where the onselect ...

Conceal the option to "show more" when there are no additional posts to display

Is there a way to dynamically hide the load button when no more posts are available? I've included my code below: function.php function load_more_posts_ajax(){ $offset = $_POST["offset"]; $ppp = $_POST["ppp"]; header("Content-Type: tex ...

How can I update a property within an object in a sequential manner, similar to taking turns in a game, using React.js?

I am currently working on a ReactJs project where I am creating a game, but I have encountered an issue. I need to alternate turns between players and generate a random number between 1 and 10 for each player, storing this random number inside their respec ...

AngularJs does not properly update the scope of a scoped directive when using ng-repeat within itself

The issue arises from calling Directive1 within the same Directive1 using ng-repeat. Although directive11 has a value in scope, when calling the nested directive with a new value, it appears to retain the initial value. I attempted to invoke the same dire ...