How to use a string condition to filter a list of objects in Javascript?

Below is the structure of the object:

var objList = [
    { "age": 19, "valueField": 34, "booleanField": false },
    { "age": 15, "valueField": 5,  "booleanField": false },
    { "age": 22, "valueField": 17, "booleanField": true }
];

Given the condition below:

var condition = 'age > 18 && age < 30 && booleanField == true';

A filter function can be used as shown here:

var newObjList = objList.filter(function(obj) {
    return obj.age > 18 && obj.age < 30 && obj.booleanField == true;
});

However, it's desired to use the condition directly without prefixing "obj." to each field.

objList.filter(function(obj) {
    return conditon; // all the fields referenced in the condition should point to the corresponding obj fields
})

This approach resembles a SQL query:

SELECT * 
FROM objlist
where " + condition + ";

The question arises: Is this achievable?

Answer №1

To create a new function callback, you can replace all existing keys within the object in condition with a specific suffix and update the return statement accordingly.

It may be necessary to add padding to the keys for replacement in order to avoid replacing unintended substrings.

var array = [{ age: 19, valueField: 34, booleanField: false }, { age: 15, valueField: 5, booleanField: false }, { age: 22, valueField: 17, booleanField: true }];
    condition = 'age > 18 && age < 30 && booleanField == true',
    cb = new Function('o', 'return ' + condition.replace(new RegExp(Object.keys(array[0]).join('|'), 'g'), 'o.$&'));

console.log(array.filter(cb));

Answer №2

Important Note:

I want to highlight at the beginning that the solution provided involves using both with and eval, which should be approached with extreme caution (only use them if you are absolutely certain that the condition string does not contain any sort of harmful code).

Here is the Solution:

To achieve this functionality, you can utilize eval along with with in the following manner:

var newObjList = objList.filter(function(obj) {
    return eval("with(obj) {" + condition + "}");
});

For Example:

var objList = [ { "age": 19, "valueField": 34, "booleanField": false }, { "age": 15, "valueField": 5,  "booleanField": false }, { "age": 22, "valueField": 17, "booleanField": true } ];
var condition = 'age > 18 && age < 30 && booleanField == true';

var newObjList = objList.filter(function(obj) {
    return eval("with(obj) {" + condition + "}");
});

console.log(newObjList);

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

What is the best way to create a function that can disable console.log and be imported into other React files for easy access?

Here is the content of my static.js file: var Helper = { console.log: function(){ }, Login: function(){ var name; var password; //rest of the code } } module.exports = Helper; Now, in my test.js file: var Helper ...

Tips for successfully implementing Angular.js validation within the confines of a <form> element

Having trouble getting my code to work when I place my app inside the <form name="myForm"> tag. Any suggestions on how to make it function properly? (It works when I place myForm inside ng-app, but my app needs to be within the <form> tag) < ...

Using Reactjs to set state with a dynamically generated key-value pair

I have a dynamic object in props that I need to transfer to state @setState key: val values: another_key: value @props.data.option: @props.data.value Unfortunately, the above method does not work as expected. I have come up with an alternativ ...

Enhancing the current Node.js, Express, MongoDB, and Socket.io stack with the integration of AngularJS

After spending some time developing a web app using Node.js, Express, MongoDB, Mongoose and Socket.io, I've successfully released version one. Looking ahead to version two, my plan is to revamp the UI completely and switch to a front-end framework lik ...

Utilizing jQuery to invoke a function at the conclusion of another function's execution

Can someone explain how jQuery can achieve the following? $('.test').css().otherThing...... etc I'm attempting to accomplish this with prototype: var myPrototype = function () {}; myPrototype.prototype.console1 = function() { console.lo ...

Is there a way to transfer a JSON object to Excel using Nextjs/React?

How can I create a button that exports data from a JSON object to multiple file formats, including Excel (.xlsx)? "data": [ { "id": 1, "temaIndicador": "Indian", "codigo": "001", "observacion ...

Next JS throwing internal server error when authenticating with axios

I'm encountering a 500 internal server error when trying to authenticate with Next Auth. I followed the documentation from Next Auth for implementation. import NextAuth from "next-auth"; import CredentialsProvider from "next-auth/provi ...

Set a maximum limit for the number of checkboxes that can be selected

If there are 10 checkboxes on a page, I am searching for a specific behavior: Use a variable called maxSelections to control the maximum number of selectable checkboxes Once maxSelections is reached, disable the other checkboxes on the page Even after re ...

Using the _id String in a GraphQL query to retrieve information based on the Object ID stored in a

Encountering an issue with my graphql query not returning anything when sending the _id as a string. Interestingly, querying the DB using any other stored key (like name: "Account 1") works perfectly and returns the object. I've defined my Account sch ...

Issue with displaying Wavesurfer.js waveform in custom Shopify section

Greetings to the Stockoverflow Community, I am facing a challenge with integrating WaveSurfer.js into a customized section on my Shopify store. Even though I have successfully implemented the section, the waveform visualization is not appearing. Link to ...

Having trouble installing the @mui/x-data-grid package in a React project

npm install @mui/x-data-grid encounters a problem that throws an error message: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" dat ...

I can't figure out why my unslider isn't adapting to the screen size. Check out the fiddle for more details

I recently implemented unslider to create a slideshow that spans 100% of the width on my website. Everything seemed to be working fine until I tried resizing the screen, and the slides remained the same size as they were initially loaded. Here is the code ...

Obtain the present location of the cursor within the TinyMCE editor

Despite various attempts, I have struggled to determine the current cursor position inside TinyMCE. My goal is to implement a change control feature that captures the starting point of text entry within the TinyMCE "textarea," allowing me to save the ente ...

Unchecking random checkboxes within a div using jQuery after checking them all

Once a link is clicked on, all checkboxes within that particular div will be checked. function initSelectAll() { $("form").find("a.selectAll").click(function() { var cb = $(this).closest("div").find("input[type=checkbox]"); cb.not(":checked" ...

Providing static files in Express while utilizing mustache templates

I'm struggling to configure Express to serve a directory of static mustache files. I have an object with data like this: { a: 'Hello :)' b: 'Goodbye :(' } Along with two files: public/a.html <div>{{a}}</div> pu ...

Is the availability of XMLHttpRequest constant?

When using XMLHttpRequest to retrieve data from the server with Javascript, is it necessary to include conditional checks for the specific browser being used? Is the code snippet below considered standard practice when working with XMLHttpRequest? if (w ...

Await keyword cannot be used due to undefined object reference

Currently in the process of implementing authentication into my node API. Using PassportJS, although I am fairly new to this so please bear with me. The goal is to add a local strategy and verify the user's password during login: // Local Strategy ...

Tips on revitalizing a bootstrap wizard

In my JSP file, I am using a Bootstrap wizard. You can see the wizard layout in the following link: The wizard allows me to add employee elements that are stored in a JavaScript array (I also use AngularJS). At the final step of the wizard, there is a su ...

Updating the state of an object within a mapping function

I've been struggling with this issue for two days now. Despite my efforts to find a solution online, I am still stuck and starting to believe that I might be missing something. The main functionality of the app is to click a button and watch an apple ...

Upcoming construction: Issue encountered - The Babel loader in Next.js is unable to process .mjs or .cjs configuration files

Within my package.json file, I have set "type": "module" and "next": "^12.2.5". In my tsconfig.json: { "compilerOptions": { "target": "ES2022", "module": "esnext ...