Remove specified JSON elements according to a designated list of permitted elements

My task involves filtering an array of allowedFields that corresponds to the keys in a JSON array created from a form.

Some fields obtained are not necessary for validation at this point, so I aim to compare the values in the JSON array with those in the allowedFields array.

JSON data received from form:

{"reference":"sdfsdfsdfsd",
"start_date":"04/22/2014",
"end_date":"05//2014",
"status":"1","frequency":"M",
"day":"sat",
"contract_type":"S",
"notice_period":"1M"}

allowedFields = array(
     reference,
     start_date,
     end_date,
     contract_type
)

In essence, my goal is to remove any fields that are not included in the allowedFields JavaScript array.

Answer №1

Step 1: Convert the JSON data into an object.

let data = '"name":"John Doe","age":30,"city":"New York"';
let obj = JSON.parse(data);

Step 2: Define the array with allowed fields.

let fieldsArray = ['name', 'age', 'city'];

Step 3: Iterate over the object and remove any keys that are not in the defined array.

for (let key in obj) {
   if (!fieldsArray.includes(key)) {
       delete obj[key];
   }
}

Step 4: Convert the filtered object back to JSON format.

let filteredData = JSON.stringify(obj);

Final Output:

{"name": "John Doe", "age": 30, "city": "New York"}

Example link

Answer №2

let data = {"name":"John Doe",
            "age":30};
let allowedProps = ['name']; // storing properties in an array

function filterData(obj, props) {
   let filteredObj = {};
   for(let prop of props) {
      if(obj.hasOwnProperty(prop)) {
         filteredObj[prop] = obj[prop];
      }
   }
   return filteredObj;
}

console.log(filterData(data, allowedProps));
>> [object Object] {
>>  name: "John Doe"
>> }

Demo

Answer №3

underscore.js solution:

_.selectFields(obj,allowedKeys)

http://underscorejs.org/#selectFields

demo

Another option is to use _.exclude(obj,string|string[]) for the opposite effect.

Working with underscore.js can significantly improve your code efficiency. While the library offers a range of functionalities, you can also choose specific tools that best suit your needs. This way, you can optimize performance without needing to reinvent the wheel.

Check out the sample implementation below (source: here)

_.selectFields = function(obj, filter, context) {
    var result = {};
    if (_.isFunction(filter)) {
      for (var key in obj) {
        var field = obj[key];
        if (filter.call(context, field, key, obj)) result[key] = field;
      }
    } else {
      var keys = concat.apply([], slice.call(arguments, 1));
      for (var i = 0, len = keys.length; i < len; i++) {
        var key = keys[i];
        if (key in obj) result[key] = obj[key];
      }
    }
    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

Vue.js error: Unable to locate requested resources

Recently, I've been encountering a curious issue when trying to access a specific component in my application. When I manually type the URL http://localhost:8080/detailed-support/start into the browser, the content loads without error. However, none o ...

Tips for removing unnecessary debugging code from JavaScript when compiling or minifying your code

Back in the day, I would always include tons of debug code in my JavaScript app. However, I'm now searching for a method that will eliminate debug code during the compilation/minification phase. Does the world of JavaScript have something similar to ...

Struggling to establish the default selection value in AngularJS

I am currently working on a project involving PHP and Angular. The values I need for a select ng-options are coming from a database. I am struggling to set a default value for the select component from the parameters. I have searched through various sites ...

Vue 2 - Error: The function is not defined at HTMLInputElement.invoker (vue.esm.js?65d7:1810)TypeError: cloned[i].apply

I encountered the following error: Uncaught TypeError: cloned[i].apply is not a function at HTMLInputElement.invoker (vue.esm.js?65d7:1810) I have set up my project using vue-cli (simple webpack), and below is the code for my component: <template ...

Using Jquery to add text at the beginning of a Gmail signature

I am currently working on creating a tool using InboxSDK, which adds text to the end of an email message just before the signature. InboxSDK provides the message body as an HTML Element, and I am experimenting with using Jquery to insert the text. The chal ...

Adding information to a MySQL database using a variable - What's the best way?

When I attempt to insert values defined in JavaScript at the beginning of the program, it seems to have an issue with me trying to input variables. Instead, it requires me to enter the raw name. The error message displayed is as follows: Error: ER_BAD_FI ...

The operation of "grunt build" results in a Lexer Error, causing the ng-include

After deploying my unminified code successfully, I proceed to run grunt build and deploy from the dist folder. However, upon checking one of the pages, I encounter a breakage with an error in the console: Error: [$parse:lexerr] Lexer Error: Unexpected nex ...

The current version of 'buffer' is outdated. To resolve this issue, please upgrade to v4.9.2 or higher

Having some trouble integrating aws-amplify and aws-amplify-react modules into my application. After running: npm install --save aws-amplify aws-amplify-react I encountered multiple warning messages related to missing or deprecated dependencies. Althoug ...

What steps should be taken to link a frontend program on a separate port to a backend system?

Placing my frontend application in the public folder of a node.js application has allowed me to fetch form-data using the following request: try { await axios.post("/api/v1/contact-form", { name, email, msg, }); } My backend, ru ...

Click on the image to resize the div accordingly

I have a scenario where I need to achieve the following functionality: Two divs are present, with an image inside the first div. When the image is clicked, the left div should resize, and the content on the right side should expand to show full page cont ...

Unleashing the power of promises through chaining resolution and rejection

My function returns a deferred.promise, following jQuery's deferred concept. Regardless of the success of the file read, I want to move on to the next step in the chain. Here's an example of how I currently handle it: var a, b, c; readF ...

Are there specific files or classes that store constants for different keyboard events?

When working in Angular, I often bind data with a host listener using code similar to the example below: @HostListener('window:keyup', ['$event']) onKeyUp(event: KeyboardEvent) { if (event.keyCode === 13) { this.onEnterClicked(ev ...

originalRenderPage has not been declared

I encountered an issue while working on my new nextjs app. The problem arose when I tried to add a carousel using props in my project, resulting in an error stating that 'originalRenderPage' in Document.js is not defined. Any assistance would be ...

Ensure the Json object contains an integer

I am facing an issue where I receive a Json data in dictionary format. Below is a sample json: Receivedtext: { "x": "pricef", "b": "usd", "ds": [ "tpr", "avgp", "mcap", "ppc7D", "ppc12h", "ppc4h", "ppc24h" ], "data": ...

Executing VueJS keyup handler after the previous onclick handler has been executed

Link to example code demonstrating the issue https://codepen.io/user123/pen/example-demo I am currently facing an issue with a text field named search_val that has a watcher attached to it. The text field includes a v-on keyup attribute to detect when th ...

Angular 4: Transform a string into an array containing multiple objects

Recently, I received an API response that looks like this: { "status": "success", "code": 0, "message": "version list", "payload" : "[{\"code\":\"AB\",\"short\":\"AB\",\"name\":\"Alberta&b ...

Changing states in next.js is not accomplished by using setState

Struggling to update the page number using setCurrentPage(page) - clicking the button doesn't trigger any state change. Tried various methods without success. Manually modified the number in useState(1) and confirmed that the page did switch. import ...

Tips on selecting a nested array in PHP

Currently, I am delving into the world of array-ception: an array within an array. The challenge I am facing involves passing hidden values from one form to another. Among these values is an array of checkbox selections that needs to be submitted to a diff ...

How can login errors be displayed in a Django application?

When I try to log into my website using the custom login page, entering the correct account details allows me access. However, if I input the wrong information, the page just refreshes with the username and password fields empty. Is there a way to display ...

Getting started with TinyMCE in Nuxt: A step-by-step guide

I need to incorporate this script into my Nuxt code: <script> tinymce.init({ selector: "#mytextarea", plugins: "emoticons", toolbar: "emoticons", toolbar_location: "bottom", menubar: false ...