Ways to programmatically append data to an object using JavaScript

My dilemma involves an object:

var myObject={};

accompanied by a function that appends values to the object:

function appendData(id, name){
    //logic to validate id and name format, specify conditions for name being "John" and id being "I23423"
    myObject.id = name;
}

However, the output consistently appears as:

myObject{
    id="john"
}

What I actually desire is for the id to reflect whatever value the user inputs, resulting in:

myObject{
    I23423="John"
}

Any suggestions on what adjustments should be made?

Answer №1

If you're looking to achieve what you're asking for, you'll have to utilize square brackets `[]` on the object as if it were an array. I'm not entirely sure why this is necessary, but that's how it works.

function(id, name){
  var obj = {};
  //any other necessary tasks;
  obj[id] = name;
  return obj;
}

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 response is dispatched without delay and does not necessitate awaiting

I am facing an issue with waiting for the completion of the getAllData function before proceeding further. let _partnerToken; async function getAllData(dealerId,id){ let partnerToken; var options = { 'method': 'GET', ' ...

Is it better to store data individually in localStorage or combine it into one big string?

When it comes to keeping track of multiple tallies in localStorage, one question arises: Is it more efficient to store and retrieve several small data points individually or as one larger chunk? For example: localStorage.setItem('id1', tally1); ...

employ identical components in v-if and v-else

Currently, I am in the process of designing a login/register page using Vue. The layout includes separate tabs for both login and registration purposes. Here is a snippet of my template code: <transition v-bind:name="TabEffect"> <div ...

jQuery - can you identify which specific object from the entire set this is?

I am curious if there is a simple method to identify which DOM object I have when it is also part of another set of objects. To illustrate, let's consider the following scenario: There are 5 div elements: <div id="1"></div> <div id="2 ...

What sets @vue/cli-plugin-unit-jest apart from vue-jest?

Can you explain the distinction between these two software bundles? @angular/cli-plugin-unit-jasmine angular-jasmin If I already have one, is there a need for the other? And in what circumstances should each be utilized? ...

What is the best way to keep a header row in place while scrolling?

I am looking to keep the "top" row of the header fixed or stuck during page scrolling, while excluding the middle and bottom rows. I have already created a separate class for the top row in my header code: view image description ...

Issue with React Material-UI Select component not displaying the chosen value

Hi there, I'm facing a problem with the MUI select function while trying to choose a country. I can see that when I select a country, its value changes, but nothing appears inside the select box. const [selectedCountry, setSelectedCountry] = useState( ...

Tips for streamlining distinct states and generalized state in UI Router

I've set up the following configuration in my JS app under the $stateProvider section using angular ui-router: .state('login', { url: '/login', templateUrl: 'app/login/login.tmpl.html', controller: &apo ...

jQuery AJAX Concurrent Event

I have encountered a problem similar to ones discussed on SO, but none exactly match my specific issue. Here's the situation: var x = 5; if( some condition ){ $.ajax({ url:"...", success: function(response){ x = respo ...

How to Delete Decimal Points from a String Using Regular Expressions

I am searching for a way in JavaScript, such as REGEX, to eliminate decimal numbers from a string. Here is an example input: Mazda 6 2.0 Skyactiv-G Wagon 2018 - Startstop.sk - TEST Mercedes C63 AMG Sound REVVING 6,3l V8 And here is the expected output: M ...

Loading external templates in Angular2 with Webpack2

Attempting to integrate ngtemplate-loader in a project using AngularJs 2 and Webpack 2 is proving challenging. While this setup has been successful in Angular 1.x projects with Webpack 1.x, it encounters an error when running in the browser: Uncaught Type ...

Here's a guide on executing both GET and POST requests using a single form

Currently, I am developing a web application which involves using a GET request to display checkboxes in a form. The selected data from the checkboxes needs to be sent back to the server using a POST request. However, I'm facing an issue with performi ...

Launch a new tab within the parent window, passing on variables from the parent window

Currently, I have a button that opens a new window in a new tab by using window.open("newpage.html"). In the child window, I use childVar = window.opener.parentGlobalVar to access global variables from the parent window. Now, I have been requested to open ...

How to handle multiple formData input in NestJS controller

How can I create a controller in Nest.js that accepts two form-data inputs? Here is my Angular service code: public importSchema(file: File, importConfig: PreviewImportConfig): Observable<HttpEvent<SchemaParseResponse>> { const formData = ...

Tips for displaying user-entered information from a form after submitting it with PHP

How can I display the email in the email text input field with this code? It doesn't seem to work correctly when there is a failed login attempt. value= "if(isset($_POST['submit'])){ ?PHP echo $_POST[''email']?>"; ...

Use jQuery to dynamically alter color based on conditional statements

What could be causing the background color not to change to green? var id; id = setInterval(changeColor, 1000); function changeColor(){ var elem= $("#target"); var color = elem.css('background-color'); if (color == &apos ...

What is the best way to enter text into the terminal following the execution of "yarn start"?

While developing a Node chat application, I encountered an issue where I am unable to type anything in the terminal after entering "yarn start". The tutorial I am following shows that the instructor can still input commands in their terminal after running ...

Generate an array containing the dates of the past 30 days using Moment.js

Currently, I am utilizing momentjs in my project and aiming to generate an array that comprises of the last 30 days. My approach involves creating a counter and subsequently iterating backwards, generating a new moment instance for each day. However, I a ...

apply a course to the designated element

Alright, I have this piece of code that deals with session and page requests. // Let's start our session session_start(); // Now let's check if there is a page request if (isset($_GET['page'])) { // If there is a requested page, we ...

Steps for extracting a portion of the current page's URL

Can someone help me extract a specific part of the current URL using JavaScript? The URL looks something like this: I need to isolate the number "3153038" from the URL and store it in a JavaScript variable. Thank you! ...