Filter out any items from the JSON data that include a designated keyword

Can anyone suggest the most efficient way to filter out objects from JSON data that contain a specific term or keyword?

Here's an example of my JSON data:

json = [{
 "name":"John",
 "age":30,
 "cars":"BMW"
},
{
 "name":"Micheal",
 "age":30,
 "cars":"Ford,BMW"
},
{
 "name":"Andy",
 "age":29,
 "cars":"Ford"
},
{
 "name":"Andy",
 "age":29,
 "cars":"Ford,Toyota"
}];

I need to remove any objects that include the keyword "BMW".

Answer №1

To achieve this, the most efficient method is to utilize Array.filter():

var list = [{ "name":"John", "age":30, "cars":"BMW" }, { "name":"Micheal", "age":30, "cars":"Ford,BMW" }, { "name":"Andy", "age":29, "cars":"Ford" }, { "name":"Andy", "age":29, "cars":"Ford,Toyota" }];

var updatedList = list.filter(({cars})=> !cars.includes("BMW"));

console.log(updatedList);

Answer №2

When it comes to removing an element from an array of objects based on a specific string, the go-to method is using Array.filter. However, another approach that can be taken is using Array.reduce like shown below:

var arr =[{ "name":"John", "age":30, "cars":"BMW" }, { "name":"Micheal", "age":30, "cars":"Ford,BMW" }, { "name":"Andy", "age":29, "cars":"Ford" }, { "name":"Andy", "age":29, "cars":"Ford,Toyota" }];

var newarr = arr.reduce((acc, elem) => !elem.cars.includes("BMW") ? acc.concat(elem) : acc, []);

console.log(newarr);

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

Every time I attempt to iterate through an array, it behaves as if it were a set. This means that adding two identical values causes the program to abruptly stop running

I'm currently working on an AngularJS program where I need to iterate through an array. Below is the code snippet: <!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">&l ...

Navigating safely with the v-model directive in Vue.js

Let's consider the input component below: <input type="text" v-model="example.modules.report.description.title"></input> See full source I don't want to manually define the object structure in the data: example: { modules: { ...

Is it possible for window.open to sometimes fail in opening a popup window?

There is a process that requires an update. In order to update a third-party database, I need to call a service provided by them. My Ajax function is working properly. Below is the code snippet for the success callback. $.ajax({ . . success : funt ...

Working with Vue: Retrieving component object attributes

Looking for a way to include a statement inside an element: v-if="currentstep < maxStep" I want to dynamically set the value of maxStep based on the number of components listed in my default export: export default { name: 'step', ...

Is a Login interface available, integrating JQuery, Bootstrap, Ajax, or ColdFusion 16?

I am currently in the process of transitioning one of my applications from an old system to a new, separate system. The Single Page App is currently built using JQuery/HTML5/CSS/AJAX on the front end and ColdFusion on the back end. Before I dive into devel ...

What is the process for setting up nested routes using React router?

I have multiple layouts that need to display different screens. Each layout has its own header, footer, and other shared elements similar pages should have. Below is the code I have created: <BrowserRouter> <Route path={['/index', &ap ...

Toggle the display of items shown before without using the next() function

If you visit this website, you will notice that I am implementing a slideToggle function on various elements. To ensure that only one element is visible at a time, I have crafted the following code: $(document).ready(function() { $( ".toggle" ).click( ...

Guide on syncing Bootstrap 4 sliders using a single set of controls

Is it possible to synchronize a bootstrap 4 carousel with controls to a carousel without any controls? 1) When the control arrows are clicked, both carousels will slide simultaneously. 2) Hovering over either carousel will pause both carousels from slidi ...

Is it possible to dynamically adjust the number of nested loops during program execution?

Is there a way to achieve this task? Where the user provides an integer value k, and I need to dynamically create a nested loop with "k" levels. Here's an example: If k = 5, then: int[] array = new int[k]; for(int i=0; i<256; i++){ for(int j= ...

Troubleshooting issue with Angular's ng-class functionality malfunctioning

I am currently working on displaying a class using ng-class in the box element of my HTML code. However, it does not seem to be functioning as expected. Can someone please help me identify what I might be doing wrong? Check out this link for reference. ...

Converting character arrays to byte arrays and then transforming them into a human-readable

I captured a character array from WireShark. Here is the array: char peer0_0[] = { 0x00, 0x00, 0x04, 0xf2, 0x5c, 0xc8, 0xd6, 0xe2, 0xe3, 0xf1, 0xf9, 0xf2, 0x4b, 0xf1, 0xf6, 0xf8, 0x4b, 0xf1, 0xf0, 0xf7, 0x4b, 0xf9, 0xf7, 0x40, 0x00, 0x00, 0x00, 0x00, 0 ...

Is it preferable to include in the global scope or the local scope?

When it comes to requiring a node module, what is the best approach? Should one declare the module in the global scope for accuracy and clarity, or does declaring it in the local scope make more sense? Consider the following examples: Global: let dns = r ...

Conceal the nearest parent element above using JavaScript (or jQuery)

I need to implement a functionality where clicking a button hides a specific HTML class. The structure of the HTML is as follows: <thead> <tr class="employee-list"> <th> <button class="show-emp">S ...

Refine JSON arrays by applying combined nested array filters

Currently, I am in the process of developing a JavaScript code that aims to filter JSON data based on a specific condition. Yesterday, I had posted a question seeking guidance on this matter How to filter data from a json response. However, since I had not ...

Troubleshooting: Issue with .NET console app failing to read config

While I was in the process of creating a .net console application that utilizes the latest ConfigurationBuilder implementation instead of the old appSettings, I encountered an issue. This is the code snippet I have: public static void Main(string[] args) ...

Exploring the beauty of Node.js/Express.js with Chunked GET Requests

My current challenge involves making a GET request on a Node.js/Express.js backend that includes 80KB of data. The issue arises because the IoT board I am using for this request has a limited RAM of only 32KB, causing lag when trying to parse such a larg ...

What is the best way to extract data from a Json file using fgets and file_get_contents in a PHP script?

I encountered an issue with parsing a JSON file in PHP, here's the sample data: { "users":[ {"username":"user123","password":"123321abc"}, {"username":"user124","password":"123321abc"}, {"username":"user125","password":"123321abc"} ] } Currently, I ...

jQuery struggles to process large response

I am currently developing an application that sends requests to a URL and parses the table found in the HTML response using jQuery. While this method works well for smaller amounts of HTML code, it runs into issues with larger datasets. The problem arises ...

Utilizing Data Binding in D3.js

Why is the text "Hello" not appearing five times on the page as expected? index.html <html> <head> <title>Data Binding</title> </head> <body> <h1>D3.js</h1> <script src="https://d3js.o ...

Tips for fetching a response after sending an ajax request using XMLHttpRequest

/* The following **frontend** function is executed to transmit a new post (in JSON) to the Node server */ addPost(postData) { const xhr = new XMLHttpRequest(); xhr.open('POST', `${process.env.REACT_APP_BACKEND}/posts`); xhr.setRe ...