A method for iterating through JSON data and assigning a specific key name to a variable based on a corresponding string

A JSON object is returned from the event.body in a function like this:

exports.handler =  async (event, context, callback) => {

{"name":"Anders","package":"Silver","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fd98909c9491bd98909c9491d39e9290">[email protected]</a>","subject":"fdsafa","weightLoss":"false","strength":"on","message":"test"}

Questioning how to iterate through and detect any false values, changing them to key names instead. For example, if the 'weightLoss' value is false, a variable var weightLoss = "weightLoss" should be created.

Pseudo code:

Map over event.body, check if any values are false, then create a new variable with the name of the key holding that false value as a string.

Additional code snippet:

exports.handler =  async (event, context, callback) => {

    const payload = JSON.parse(event.body)

    const body1 = event.body;

    Object.entries(body1).forEach(([key, value]) => {
    if (value === 'false') {
        body1[key] = key;
    }
    });

    console.log(body1);

    const { email, subject } = payload

    ...

The output will vary based on form field checks, for example:

Field checked:

{"name":"Anders","package":"Silver","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="97f2faf6fefbd7f2faf6fefbb9f4f8fa">[email protected]</a>","subject":"fdsafa","weightLoss":"on","strength":false,"message":"fdsasfdsdafsdafasdfasd"}

Field unchecked:

{"name":"Anders","package":"Silver","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="57323a363e3b17323a363e3b7934383a">[email protected]</a>","subject":"fdsafa","weightLoss":false,"strength":false,"message":"fdsasfdsdafsdafasdfasd"}

Answer №1

One way to approach it could be:

const data = {"name":"Elena","plan":"Gold","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="345159555d58745159555d581a575b59">[email protected]</a>","subject":"new message","weightGain":"false","flexibility":"on","message":"sample text"};</pre>
Object.entries(data).forEach(([key, value]) => {
  if (value === 'false') {
    data[key] = key;
  }
});
console.log(data);

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 UseEffect function is displaying an inappropriate value, however, it only occurs once

My goal is to display the state value whenever the password is changed using the useEffect hook in React. It's working fine for the password, but the issue arises when I try to change the email. The console also renders the email value, which is not i ...

Removing leading zeros from numeric strings in JSON data

I am facing an issue with my jQuery-based JavaScript code that is making an Ajax call to a PHP function. updatemarkers.xhr = $.post( ih.url("/AjaxSearch/map_markers/"), params).done( function(json) { <stuff> } The PHP function returns the follo ...

Remove elements from JSON string created from a PHP array

In my code, there is a PHP function called $users->getFullUserList('json') which returns a JSON string containing user data. This data is created from a PHP Array using json_encode($this->userListArray) Before it is converted into a JSON s ...

Efficient ways to temporarily store form data in React JS

When filling out a registration form and clicking on the terms and conditions link, the page redirects to that content. Upon returning to the registration page, all fields are empty and need to be filled in again from scratch. I am looking for a way to ha ...

Trouble with smooth shading on OBJ file when loaded into Three.js environment

It's interesting how the OBJ appears smooth in my 3D modeling software but looks somewhat quirky and triangular in the Three.js scene. I've applied MeshLambertMaterial to it, which supposedly uses THREE.SmoothShading as its default shading. Despi ...

Replace a function within the UI-Bootstrap framework

Incorporating the angular-bootstrap library into my app via bower has been a game changer. Although I am currently stuck with an (outdated) version that includes a pesky bug, upgrading is not yet feasible in my scenario. I considered inserting a customiz ...

How secure is the PHP login system?

Regarding the security of this login page, I am conducting research on SQL injection vulnerabilities. If there is a vulnerability, how can it be managed? I have previously encrypted user details and stored them in a local file. I am considering moving to ...

Using Angular's $post method to communicate with PHP CodeIgniter for making requests and handling responses

I am having trouble sending data from Angular to Codeigniter using $post. Here is the JavaScript code I am using: $scope.user.first_name = 'first name'; $scope.user.last_name = 'last name'; $http({ method: 'POST', ...

What could be causing the issue of being unable to connect to the NodeJS express server from any network?

Imagine having a web server running on port 3001 with the IP address 23.512.531.56 (obviously not a real one) and then switching to another network, like your neighbor's. Now, when you try entering 23.512.531.56:3001 in Chrome, why doesn't the se ...

Cross-Origin Request Sharing (CORS) problem encountered while making an API call with

My current challenge involves calling an API that returns data in XML format as a response. While testing the .htm file on my local machine, I encountered the following error. https://i.stack.imgur.com/FsvZ0.png Similarly, running it from the codepen.io ...

Update the text on a Button component using ReactJS

I am looking to update the text displayed on the Check All button to say Uncheck All after all the checkboxes have been checked. Below is my code. Any recommendations?” checkAllCheckBox = () => { let {todos} = this.state let newArray = [.. ...

Angular 16: ngCharts Error - Unable to Iterate Over registerables Property

ERROR: Uncaught (in promise): TypeError: chart_js__WEBPACK_IMPORTED_MODULE_0__.registerables is not iterable (cannot read property undefined) TypeError: chart_js__WEBPACK_IMPORTED_MODULE_0__.registerables is not iterable (cannot read property undefined) at ...

Yummly API delivers unexpected characters within JSON data output for Android applications

When I access the Yummly recipe database in my Android app, I use the following html query: http://api.yummly.com/v1/api/recipes?_app_id=MY-APP-ID_app_key=MY-APP-KEY&q=KEYWORD While the documentation claims that GET requests are returned in UTF-8 for ...

Encountering a TypeError

Every time I try to submit a form request, I encounter an error [TypeError: object is not a function]. The problematic code lies within my hiren-conf.js file. Here's a snippet of the Mongoose code: var auth = require('../auth.js'); var mong ...

Making a node.js API call using multipart/form-data

Submitting Data Using POST https://i.sstatic.net/iVTDd.png Node.js Data Capture Method without the Use of Express and Body-Parser FORM DATA: ORDERID: MID: TXNID: TXNAMOUNT: 5.00 PAYMENTMODE: NB CURRENCY: INR TXNDATE: 2021-06-14+23%3A02%3A30.0 STATUS: ...

Retrieving particular excerpts from a block of text that includes the keyword "javascript."

I have a chunk of string containing HTML source code. Currently, I am trying to read specific tags that I need using JavaScript. Since I am new to programming, I'm unsure how to proceed. Can anyone assist me with this? The issue lies in the following ...

Facing unexpected behavior with rxjs merge in angular5

import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/merge'; this.data = this.itemsCollection.valueChanges() this.foo = this.afs.collection<Item>('products') .doc('G2loKLqNQJUQIsDmzSNahlopOyk ...

Importing a geoJSON object directly onto Google Maps V3

I am currently working on developing a map using floor plans stored in mongodb. Instead of saving the JSON data into a file and calling it with map.data.loadGeoJson('myfile.json'), I want to create an object directly for better efficiency. Below ...

Show loading GIF on the screen and hide it once the script has finished loading

I have implemented lazy loading for my Facebook comments plugin, but I am facing an issue where the plugin takes some time to load. To provide a better user experience, I want to display a loading GIF while the plugin is loading. However, once the comments ...

What is the process for obtaining a push key in Firebase?

When a user submits data to the Firebase database, I need to handle the Key generated by that action in my own function. The challenge arises when a user fills out a form and sends data to our real-time DB. This data may include optional images, and I wan ...