Tips for dynamically sending data without explicitly stating the name:

Looking to create a JSON structure with name and value pairs such as name:"john".

Check out the code snippet below:

var allFields = [];
var inputs = document.getElementsByTagName('input');
for(var i=0; i<inputs.length;i++){

        name = inputs[i].name;
        item = inputs[i].value;
        allFields.push({name: item});
}
var alleFelder = JSON.stringify(allFields);
alert(alleFelder);

The issue I'm facing is that "name" is hardcoded into the JSON.

Instead of having: name:"john", lastname:"brooks", birthdate:"1.1.1999"

I end up with: name:"john", name:"brooks", name:"1.1.1999"

Answer №1

You can easily enhance the functionality of your object by using this straightforward function to assign new key-value pairs.

const myObj = {}


function insertKeyValue(obj, key, value){
  obj[key] = value;
}

const keys = ["title", "author"];
const values = ["The Great Gatsby", "F. Scott Fitzgerald"];



for(let i = 0; i < keys.length; i++)insertKeyValue(myObj, keys[i], values[i])

console.log(myObj)

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

Developing a report in RDLC using a JSON array

My current project involves creating an RDLC report using a JSON array obtained from an API. While I have experience generating RDLC reports by directly accessing an SQL database through a Dataset, I am facing challenges in working with the API data that r ...

Exploring the functionality of arrays within Selenium IDE

Recently delving into Selenium IDE, I am a beginner and looking for guidance. The challenge at hand: How can I access values from an array generated by execute script | var array1 = document.getElementsByClassName("Post"); return array1; | array1 Initi ...

Support for Big Decimal in Org.json

Is there a way to add BigDecimal support to the org.json library? I'm attempting XML to JSON conversion using this library, but it seems to be lacking Big Decimal support. Any suggestions on how to handle this issue? Even after trying the 20200518 ve ...

Using jQuery to gently fade out text at the top and bottom of the page as you scroll

I am seeking a way to fade out the content of my page with an opacity/rgba color effect as it approaches a specific distance from both the top and bottom of the viewport. This is the desired outcome I want: In the example above, there is a gradient posit ...

The term 'Buffer' is not recognized in the context of react-native

Having trouble using buffer in my react-native app (developed with the expo tool). I have a hex value representing a geography Point like this for example -> 0101000020E61000003868AF3E1E0A494046B3B27DC8F73640 and I'm attempting to decode it into l ...

Adjusting or cropping strokes in a JavaScript canvas

I am working with a transparent canvas size 200x200. The object is being drawn line by line on this canvas using the solid stroke method (lineTo()). I'm in need of making this object full-width either before or after ctx.stroke();. https://i.sstatic. ...

Extract the text and value from an asp.net treeview by utilizing jQuery or JavaScript

On my website, I am using a TreeView controller. I have disabled node selection by setting SelectAction = TreeNodeSelectAction.None as I have the checkbox option enabled. However, this causes an error when trying to access the .href property of the node. T ...

Exploring the Dynamics of AngularJS: Leveraging ng-repeat and ng-show

Recently, I came across this code snippet: <div class="map" ng-controller="DealerMarkerListCtrl"> <a ng-click="showdetails=!showdetails" href="#/dealer/{{marker.id}}" class="marker" style="left:{{marker.left}}px;top:{{marker.top}}px" ng-rep ...

Error occurred while attempting to run 'postMessage' on the 'Window' object within GoogleTagManager

Recently, I encountered an error stating "postMessage couldn't be cloned". This issue seems to be affecting most of the latest browsers such as Chrome 68, Firefox 61.0, IE11, and Edge. Error message: Failed to execute 'postMessage' on &ap ...

Set a restriction on the Bootstrap DatePicker to only show dates within a

My application features StartDate and EndDate datepickers, and I need to implement a 30-day limit on the selection range to prevent performance issues caused by loading too much data. I'm looking for a functionality where if the user picks today as t ...

Send a JSON form without using AJAX

Is there a way to send form data as JSON without relying on AJAX? I attempted changing the enctype attribute: <form enctype="application/json"></form> However, according to w3schools, this is not a valid value. The reason behind my query is ...

Take the user input from the form and incorporate it into the URL for the AJAX request

How can I dynamically update the URL in the AJAX call asynchronously? I've made a few attempts, but none of them seem to work. This is the current code: <!-- Input form --> <form class="navbar-form navbar-left" role="search" id="formversion" ...

Adjust css style based on the current time of day

I recently came across this fascinating tutorial that demonstrates an animation changing from day to night every 30 minutes. The concept is very appealing, but I began contemplating how to adapt this animation to reflect real-time changes between day and ...

Is it possible to format JSON nicely in Swift or Obj-C even without prior knowledge of its structure?

Instead of using the JSONSerialization.WritingOptions.prettyPrinted option in this way: do{ let json = try JSONSerialization.jsonObject(with: data, options: []) as! [String:AnyObject] let prettyJson = try JSONSerialization.data(withJSO ...

Typescript double-sided dictionary: a comprehensive guide

Looking for a dual-sided dictionary implementation in TypeScript that allows you to retrieve values using keys and vice versa. An initial approach could be storing both items as keys: dict = {"key": "value", "value": "key"} But I am curious if there are ...

What is the method of displaying a querystring on my Angular view page without relying on a controller?

My experience lies in utilizing AngularJS 1. This excerpt showcases the stateprovider configuration present in my config.js file: JavaScript .state('projects', { abstract: true, url: "/projects", templateUrl: "views/common/master_pa ...

The TextField is currently unable to be edited because of an Uncaught TypeError stating it is not iterable

Currently, I am fetching data from an API and updating TextFields with it for display. My goal is to allow users to edit the data shown in these TextFields, but I keep encountering a Uncaught TypeError: prev.fields is not iterable error whenever I attempt ...

CodeIgniter 3 fails to handle jQuery ajax calls

I am currently tackling an ajax request issue in CodeIgniter 3. The task involves clicking on a checkbox to trigger the changVisib() function. Upon reviewing the code snippet, everything appears to be functioning correctly as the alert() is being executed. ...

What is the best way to implement lazy loading for grandchildren in a dynatree structure?

There is a specific requirement that sometimes I need to load not only the children, but also the grandchildren and if possible their children in lazy loading. Is this feasible? When creating a JSON response for lazy loading, can I structure it like this? ...

Changing text inside ion-header-bar directive

When utilizing the ion-header-bar directive, I have the left side designated as class="button", the middle section containing <h1> with the word "Recent", and the right side as <ng-icon>. The text on the left side is dynamically generated usin ...