Is there a way to transform a JavaScript array into a 'name' within the name/value pair of a JSON object?

Suppose I have a dynamic array with an unspecified length, but two specific values are given for this array.

var arrName = ["firstName","lastName"];

I need to create a JSON variable that includes the exact values provided for this dynamic array. Here are my two approaches:

Method 1: Encounter Error Unexpected type '['

var jsonValues = {arrName[0] : "Mark", arrName[1]: "Collins"}

Method 2: This method works, but when I type 'jsonValues' in the console, it doesn't display the JSON contents; instead, it shows an Array type. I am unsure if this is acceptable because I intend to JSON.stringify it and send it via ajax to the PHP server.

var jsonValues = [{}];
jsonValues[arrName[0]] = "Jeffrey";
jsonValues[arrName[1]] = "Douglas";

Answer №1

Do you desire

let objValues = {};
objValues[arrKeys[0]] = "Jennifer";
objValues[arrKeys[1]] = "David";

If you're looking for a more versatile solution, check out the object function in Underscore.

In ES6, which is still lacking widespread browser support, there's now syntax that accomplishes your initial goal:

let objValues = {
  [arrKeys[0]]: "Jennifer",
  [arrKeys[1]]: "David",
};

Refer to MDN Reference

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

Which is better for cycling through a list of items: CSS or JavaScript?

Currently, I have a navigation bar set up as an unordered list (<ul>), but some list items are not visible. I want to implement functionality where clicking arrows will move the elements left or right by hiding or showing the leftmost or rightmost it ...

Ensure that the input remains below ten

My goal here is to ensure that the value in an input element is a non-zero digit (0<x<=9). Here's the HTML tag I'm using: <input type="number" class="cell"> I've experimented with various JavaScript solutions, but so far none h ...

Adding items to a JSON document

My task involves creating a pseudo cart page where clicking on checkout triggers a request to a JSON file named "ordersTest.json" with the structure: { "orders": [] }. The goal is to add the data from the post request into the orders array within the JSO ...

What is the best way to ensure that the swf loads only after all the images and text have loaded completely

Is there a way to use jQuery to control the loading of SWF files on my CMS system? Sometimes when a video is included in the SWF file, it uses up bandwidth and makes the page non-responsive for a while. I would like the SWF files to load after the other co ...

You are unable to assign mutations in Vuex

Dealing with a peculiar problem where "val" and "ok" can be used within "console.log()", but for some reason, state.user cannot be assigned any value. However, state.user does display 'ok' on the website. export const state = () => ({ user: ...

Design a clear button for MUI autocomplete feature

I'm currently working on a project where I need to implement a button that clears the MUI autocomplete value and removes the data from the UI. Although I've managed to delete the data from the UI with the code provided, the onChange value remain ...

Arranging an array containing three elements

As I work on my angular app, I have come across the following array: [ { "Name": "Jack", "IncomingTime": "2020-06-19T11:02+00:00", "Outgoingtime": "2020-06-19T11:07+00:00" ...

Showcase PHP associative arrays specifically containing the key named 'name'

My title may seem a bit unclear, but I'm struggling to find the right words to describe it. Essentially, what I'm trying to convey with the term "array name" is exemplified in this code snippet: array (size=3) 'arrayname0' => ...

Can you explain the variance between using querySelector() and getElementById/getElementsByClassName/getElementsByTagName()?

I'm confused about the distinction between using querySelector() and getElementById(). From what I understand, querySelector is able to retrieve an element using any selector, giving it more flexibility. Are there additional contrasts between the two ...

The functionality of cloning in jQuery may encounter an issue where the text field remains enabled if the user selects an option labeled "other

Currently, I am working on a jQuery clone with my existing code and everything is functioning well. In the first scenario, if the user selects other from the dropdown menu, the text field becomes enabled. In the second scenario, when the user clicks ...

Tips for assigning a standard or custom value using JavaScript

What is the best way to automatically assign a value of 0 to my input field when the user leaves it blank? Should I use an if statement { } else { } ...

Boosting autocomplete speed by storing the JSON response in a cache for enhanced performance

Currently, I am utilizing the FCBautocomplete plugin for auto-complete functionality. However, I have noticed that with each character entered into the field, a request is sent to the server for results. With my large dataset, this raises concerns about po ...

Having trouble with incorporating a feature for uploading multiple images to the server

At the moment, I have a code snippet that allows me to upload one image at a time to the server. However, I am looking to enhance this functionality to be able to upload multiple images simultaneously. I am open to sending multiple requests to the server i ...

Utilize Vue.js to selectively display or manipulate objects with a

I am currently working on a Vue.js component page that receives data from my backend. The page consists of three different filters/states that users can choose from: Unlabeled, Completed, and Skipped. Unlablled Completed Skipped My approach involves usin ...

Mastering the art of configuring AngularJS: A beginner's guide

Exploring the world of angularJS, I have encountered the config function which presents two different argument structures as shown in the following example. Example 1 dashboardApp.config(function($stateProvider, $urlRouterProvider) { //$urlRouterProvider ...

Stop all AJAX calls and timers immediately

I need to terminate an ajax request along with its timer that is being executed within a function: var run_timer; var run; function myrequest() { if(run && run.readystate != 4){ run.abort(); } run = $.ajax({ type:"POST", ...

Firefox does not process Ajax requests in the same way as other browsers

On my (mvc) website, I have some code that uses Ajax to retrieve information. Everything works smoothly in most browsers except for Firefox. For some reason, Firefox bypasses the Ajax controller and goes straight to the default controller. $('.navba ...

Using React.js to pass data iterated with map function to a modal

I am trying to display my data in a modal when clicking on buttons. The data is currently shown as follows: 1 John watch 2 Karrie watch 3 Karen watch ... like this It is presented in the form of a table with all the 'watch' items being button ...

Experience the captivating AUTOPLAY feature of the mesmerizing FULLSCREEN SLIT SL

I am currently utilizing a slider that is functioning well, however I am encountering an issue with autoplay. Whenever I click on the navigation arrow or Nav dot at the bottom of the slider, the autoplay feature stops working. For more information, please ...

Using Highcharts to dynamically color a map based on data values in a React TypeScript project

I'm attempting to generate a map where each country is filled with colors based on its specific data, similar to the example shown in this map. I am looking for a functionality akin to the use of the formatter function within the tooltip. I have expe ...