Iterate through an array of objects and if a specific property matches a certain condition, extract that particular object - Using

I have an array of objects that I need to iterate through. If a match is found, I want to slice that object.

var object = [
    {
        "Name": 'Kshitij',
        "LastName": 'Rangari',
        "CountryBorn": 'India',
        "CountryStay": 'USA'
    },

    {
        "Name": 'Pratik',
        "LastName": 'Rangari',
        "CountryBorn": 'India',
        "CountryStay": 'Canada'
    },

    {
        "Name": 'Pratibha',
        "LastName": 'Rangari',
        "CountryBorn": 'India',
        "CountryStay": 'India'
    },

    {
        "Name": 'Ankita',
        "LastName": 'Raut',
        "CountryBorn": 'India',
        "CountryStay": 'Australia'
    },

    {
        "Name": 'Wayne',
        "LastName": 'Rooney',
        "CountryBorn": 'UK',
        "CountryStay": 'UK'
    }
]

console.log(object);

object.forEach(function(x){
  if (x.Name==='Kshitij'){

  }
})

object.map(obj => {

    obj.AllFirstName = obj['Name'];
    console.log(obj['AllFirstName']);
})

console.log('------------------------------')

console.log(object); 

I need to loop through the objects in the array and remove those with Name === 'Kshitij' and Name ==='Pratik'.

How should I go about achieving this?

Answer №1

If you want to create a new array that filters out certain values based on a specific key in the objects, you can use the following function.

const filterByKey = (key, values) => object => !values.includes(object[key]);

var data = [{ Name: 'John', Age: 25 }, { Name: 'Emily', Age: 30 }, { Name: 'Michael', Age: 28 }];

console.log(data.filter(filterByKey('Age', [25, 30])));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

Employ the built-in filtering function to eliminate any elements that meet specific criteria. Subsequently, assign the updated list back to the original object.

const namesToExclude = ['Ethan', 'Liam'];
object = object.filter(item => !namesToExclude.includes(item.Name))

Answer №3

Utilize the filter() method to create a new array without certain objects - view example below:

var people=[{"Name":'John',"LastName":'Doe',"CountryBorn":'USA',"CountryStay":'Canada'},{"Name":'Jane',"LastName":'Smith',"CountryBorn":'UK',"CountryStay":'Australia'},{"Name":'Alice',"LastName":'Johnson',"CountryBorn":'Canada',"CountryStay":'USA'},{"Name":'Bob',"LastName":'Brown',"CountryBorn":'Australia',"CountryStay":'UK'}];

var filteredPeople = people.filter(function(person){
  return person.Name !== 'John' && person.Name !=='Jane'
});

console.log(filteredPeople);
.as-console-wrapper{top:0;max-height:100%!important;}

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 concept of Event Flow in JavaScript

When an element within another element has a click handler attached, clicking the inner element will trigger its click handler first and then bubble up to the parent element to execute its click handler as well. This is my interpretation of the process. I ...

Is it possible to eliminate all zeros from an array list?

Currently, I have the following code snippet: List<String> lineList = new ArrayList<String>(); String thisLine = reader.readLine(); while (thisLine != null) { lineList.add(thisLine); thisLine = reader.readLine(); } System.out.println( ...

What is the method to transmit just the shift key in JavaScript?

Is there a method to specifically send the shift key in Javascript without combining it with another key? I am aware that I can detect the presence of the shift key using evt.shiftKey, but how can I actually transmit just the shift key? I attempted: $.e ...

Show the button when the mouse moves over the image

Here is the snippet of code I am working with: <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server"> <script src="Js/jquery.min.js"></script> <script type="text/javascript"> $(document).r ...

What is the functionality of Google Chrome's "New Tab" iframes?

Have you ever wondered about those 8 small iframes displaying your most visited websites? How do they capture snapshots of the websites? How are the websites chosen for display? And most importantly, how do they actually work? Edit: I want to learn how to ...

Ensuring Type Safety in Typescript

I have a specific requirement where I need to validate the structure of a request body to ensure it conforms to a predefined type. Is there a way or a package that can help achieve this validation? type SampleRequestBody = { id: string; name: string; ...

A guide on achieving server-side rendering in React despite facing various conflicts with React Router versions

I encountered an error while trying to implement server-side rendering with React and react-router-dom. The error message You should not use Switch outside a Router has me puzzled. I suspect it might be due to a version conflict, but I'm searching for ...

Tips for passing parent component state data to a child component using a variable

In my index.js file, I have a parent component with a state variable x:[] that contains data [{…}, {…}, {…}]. Now, in my child component (child.jsx), I need to save this parent component data [{…}, {…}, {…}] in a variable within the child compo ...

Unraveling and interpreting all incoming requests to my Node.js application

Looking for a simple method to identify and decipher all encoded characters in every URL received by my Node.js application? Is it possible to achieve this using a middleware that can retrieve and decode symbols such as & ? ...

Endless spirals within the confines of an angular controller

Every time I launch my app in a window, it gets caught in an endless loop where angular continuously calls the GameCtrl and ultimately freezes the window. Here is the code snippet causing the issue: index.html <!DOCTYPE html> <html ng-app="baseba ...

What is the best way to define a variable within a function?

Here's a function designed to verify if the username has admin privileges: module.exports = { checkAdmin: function(username){ var _this = this; var admin = null; sql.execute(sql.format('SELECT * FROM tbl_admins'), (err, result, fields ...

The submission of the form with the ID "myForm" using document.getElementById("myForm").submit() is

<form name="formName" id="formName" action="" method="post" autocomplete="off"> <input type="hidden" name="text1" id="text1" value='0' /> <input type="button" name ="submit" onClick="Submit()" value="submit"> ...

React does not play well with the Sendgrid Node.js library

Seeking assistance with integrating node.js to handle email sending on my website. Interested in having the email form immediately send upon submission, rather than using the standard "mailto" action. Utilizing Sendgrid as the email service for API and ser ...

Does Node Express call the next middleware immediately when the next function is called?

Can someone please help me grasp the concept of how the next function operates within the Node Express framework? I know that we utilize the next function within the current middleware to trigger the execution of the subsequent middleware listed. These mid ...

Which regular expression can match both the start and finish of a string?

I need help with editing a DateTime string in my TypeScript file. The specific string I'm working with is 02T13:18:43.000Z. My goal is to remove the first three characters, including the letter T at the beginning of the string, as well as the last 5 c ...

Create a chronological sequence for a collection of images captured by an IP camera

I am working on creating a timeline/timeslider to showcase images captured by IP cameras. The search results for these images will be saved as events in a JSON object with details such as image capture datetime and image source: { { id:"1", sta ...

Tips for transferring data from a bitmap array to an integer array

I have a bitmap array with 6 images that I need to convert into circular images and store in an integer array. I am using a for loop to iterate through each element and apply the method to get circular images after each iteration. Now, I am looking to sto ...

Tips for updating a plugin from phonegap 2.5 to the most recent version 3.1, and the steps to follow when including a new plugin in phonegap

$('#sendSms').click(function(e){ alert("Sending SMS in progress");//After this alert, I encountered continuous errors and couldn't determine the root cause var smsInboxPlugin = cordova.require('cordova/plugin/smsinboxplugin'); ...

React automatic scrolling

I am currently working on implementing lazy loading for the product list. I have created a simulated asynchronous request to the server. Users should be able to update the page by scrolling even when all items have been displayed. The issue arises when ...

Images failing to load in jQuery Colorbox plugin

I am having an issue with the Color Box jQuery plugin. You can find more information about the plugin here: Here is the HTML code I am using: <center> <div class='images'> <a class="group1" href="http://placehold.it/ ...