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

Is there a quicker way to convert integers to strings?

Within my code, there is an array named skj that consists of 2 million rows of numbers (2000000x1 uint32). My goal is to perform the following operation: string_skj = num2str(skj); Executing the above line currently takes approximately 1 minute. Is ther ...

The function is missing a closing return statement and the return type does not specify 'undefined'

It seems like the function lacks an ending return statement and the return type does not include 'undefined'. In a recent refactoring of the async await function called getMarkets, I noticed that I had mistakenly set the return type as Promise: ...

Modifying text dynamically in AngularJS by cycling through an array of strings

Is it possible to create a text carousel in my angular controller without using an infinite loop? For example: //html <span> {{ notes }}</span> //angular controller var i = 0; var array = ["A", "B", "C", "D", "E"]; while (true ...

Threejs: Illuminating the spotlight with visibility

For my current project, I am attempting to create a visible spotlight similar to the one used by Batman. I want that cone of light that pierces through the night sky. Unfortunately, I do not have any experience with graphics or 3D design, so I am strugglin ...

Failure to Load Data Using AJAX Request

I'm currently working on validating the entered username and email by checking them against the database for availability. The email validation is working perfectly. I'm using similar code for the username, just with different id tags: Below is ...

Why is the defaultDate property not functioning properly in Material-UI's <DatePicker/> component with ReactJS?

I recently implemented the <DatePicker/> component from Material-UI ( http://www.material-ui.com/#/components/date-picker ) in my project. I encountered an issue while trying to set the defaultDate property to the current date on my computer, as it r ...

When working with Angular 2 and Typescript, a common error message that may be encountered is "TypeError

Currently diving into Angular 2 and encountered a stumbling block while attempting to create a service. Despite my efforts in finding a solution, I seem to be missing something crucial. Error: A problem arises in angular2-polyfills.js:1243 with the error ...

The face textures are not being applied correctly to the model imported in THREE.js

I'm having trouble importing a model exported from blender using the THREEJS exporter. The model loads correctly in my scene with the materials applied, such as the car appearing yellow and the glass being transparent as intended. However, I am facin ...

Load additional slides in bxslider, monitor when it has reached the last one

I am using a horizontal carousel slider with bxslider, and I have disabled the infiniteLoop feature to prevent the slider from looping. My goal is to fetch additional slides via an AJAX request and add them to the slider once it reaches the end of the cu ...

Trouble with nested components not refreshing correctly within VueJs

I've just started working with Vue and I'm currently developing a forum-style application that allows nested comments. Within this structure, there are two main components: PostForum and Comment. The PostForum component consists of an input box f ...

Guide to transferring a series of numerical data from a website to a server through an Ajax request

I'm facing an issue with my ajax implementation. I am trying to send an array of integers that are selected using checkboxes. The array is populated correctly, but when it is sent to the controller method, it becomes null. Here is the Ajax code snipp ...

How can I prevent anchors from performing any action when clicked in React?

My dilemma involves this HTML element: <a href onClick={() => fields.push()}>Add Email</a> The purpose of the href attribute is to apply Bootstrap styles for link styling (color, cursor). The issue arises when clicking on the element caus ...

Encountering issues when trying to build a Nestjs app with node-crc (rust cargo) in Docker

I am encountering an issue with building my Nest.js app using Docker due to a dependency called "node-crc" version "2.0.13" that fails during the docker build process. Here is my Dockerfile: FROM node:17.3.1-alpine RUN curl https://sh.rustup.rs -sSf | sh ...

Populating a clickable list and form with a complex JavaScript object

I have a code snippet that takes an unstructured String and parses it into a JavaScript object. My next step is to integrate it into a web form. You can check out the demo here. The demo displays the structured object hierarchy and showcases an example of ...

Tips on Including a Custom Header in an Ajax Request for a Cross-Domain JsonP Call

Is there a way to add a custom header using an ajax call in jQuery for a cross-domain JSONP call? I am making a web service call in an HTML page using Ajax cross-domain call. I am currently using JSONP and now need to send some parameters in the header. ...

Axios fails to capture and transmit data to the client's end

I created a backend using Express to retrieve Instagram feed images and then send their URLs to my front end, which is built with ReactJs. When I fetch the image URLs with instagram-node and send them to the front end, everything functions as expected. How ...

What is the best way to dynamically change the color of my component depending on the prop passed to it?

I am facing an issue with the color of my component changing based on the value of the prop 'level'. Despite using states to set the backgroundColor, all components end up having the same color due to the state being altered for every comment. I ...

Guide on transforming Json information into the preferred layout and iterating through the loop

Currently, I am diving deep into the world of JSON and feeling a bit puzzled by data formats, arrays, objects, and strings. First things first, I'm in need of data structured like this (on a jQuery page). Would this be considered an object or an arra ...

Encountering the error message "myFunction variable is not declared" when using Google Closure Compiler

When attempting to compile two JavaScript files that both use a function declared in only one of the files, an "undeclared" error is returned. To solve this issue, I added the function declaration to my externs file like this: var myFunction = function() ...

Attempting to trigger CSS transitions using JavaScript will not be successful

I'm facing an issue where CSS transitions do not work as expected when triggered by JavaScript. let isSearchBarOpen = false; function toggleSearchBar() { if (isSearchBarOpen) { searchBar.style.display = "none"; } else { searchBar.sty ...