What are some ways to duplicate values in a JavaScript array?

In this code snippet, I have two arrays and I want to combine them into another array called data:

data=[];
atIndex=0;
//userInfo contains the user's name and last name:
userInfo=['Mohammad','Kermani'];
//userKnow contains the information that the user knows:
userKnow=['php','javascript'];

data[atIndex]=userInfo;

data[atIndex]=userInfo;
data[atIndex]=userKnow;

//I intend to send the data using JSON and decode it with PHP:
console.log(data);

However, only the last data is stored in the data array.

It appears that it might be a nested array or two-dimensional array.

DEMO

Answer №1

One option is to organize the data as an array of objects...

data[atIndex] = { userInfo: userInfo, userKnow, userKnow };

This way, you can access the information like this:

var userInfo = data[0].userInfo;
var userKnow = data[0].userKnow;

Your JSON structure would look similar to this (formatted for readability):

[ 
    { userInfo: ['Mohammad', 'Kermani'], userKnow: ['php', 'javascript'] }
]

If you want to include user information and their knowledge in one object, consider the following structure:

var userObject = {
    name1: 'Mohammad',
    name2: 'Kermani',
    userKnow: ['php', 'javascript']
};

You can use this object like this:

userObject.name1 = 'my name';// set name1
var name2 = userObject.name2;// get name2

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

Disabling a second drop down field upon selecting an option in the first drop down

I have implemented a feature in my code where selecting an option from drop down one automatically updates drop down two. However, I now want to restrict users from manually editing drop down two. You can check out the live example here. var objArray = ...

What is the process for initiating printing in a separate window?

Is there a way to modify the code below so that when I click "Print" it opens in a new window instead of redirecting and losing the original receipt? <div class="print_img"> <button onclick="myFunction()"> <div align="justify ...

Search through a JSON array to find a specific element and retrieve the entire array linked to that element

Recently, I've been working with a json array that dynamically increases based on user input. Here's a snippet of the json code I'm dealing with: [{"scheduleid":"randomid","datestart":"2020-06-30",&quo ...

Mastering the art of simultaneously running multiple animations

Utilizing two functions to apply a Fade In/Fade Out effect on an element. Confident in the functionality of both functions, as testing them sequentially in the Console proves their effectiveness. However, executing: fadeIn() fadeOut() seems to result in ...

Unable to render preview image in ReactCrop

When looking to add an image cropping feature to my web application, I discovered that react-image-crop is the ideal npm package for this task. However, I'm facing an issue where the preview generated by the ReactCrop component isn't appearing on ...

Boost the elements' worth within an array

Assume I am working with an array shown below... let myArr = [0,0,2,0,0]; I am aiming to generate a ripple effect where the modified array becomes [0,1,2,1,0] ...

What are the best ways to engage with a div element using keyboard shortcuts?

Is it possible to enable keyboard shortcuts for interacting with div elements? I am working on a project tailored for seniors who may have difficulty using a mouse. Is there a way to utilize keyboard shortcuts to click on divs and access their contents? H ...

What is the best way to extract all strings located between specific substrings in Python and then convert the extracted data into a CSV format?

I am currently working on parsing the output of an API call in python. {'data': [{'type': 'infra_process_running', 'name': 'Custom Plugin Alert - Stopped Running', 'enabled': True, 'filter&a ...

"Failed to insert or update a child record in the database due to a SQL

I encountered an issue while trying to perform the following transaction: static async save(habit){ await db.beginTransaction; try { await db.execute('SELECT @habitId:=MAX(habits.habitId)+1 FROM habits'); await db.execute( ...

Guidance on Implementing Promises in Ionic 2 and Angular 2

Here are two functions that I need to implement: this.fetchQuizStorage(); this.retrieveQuizData(); fetchQuizStorage() { this.quizStorage.getAnswers().then(data => { return data; }); } retrieveQuizData() { this.quizData.getQuiz().t ...

Deleting Data with Django Rest Framework Datatables

Query I am trying to send a list of ID's to the default Django Rest Framework API URL using the rest_framework router. Everything seems to be in order until the point of submitting the ID's for deletion. Upon clicking the delete button, the DELE ...

Material-UI: Error - getMuiTheme function is not defined

After recently updating my material-ui to version 0.15.4, I encountered an issue while trying to make it work. The error message states that getMuiTheme is not a function, despite the fact that the relevant JavaScript file is present in the folder location ...

What is the most optimal jQuery code to use?

Just wondering, which of the following code snippets is more efficient (or if neither, what would be the best way to approach this)? Background - I am working on creating a small image carousel and the code in question pertains to the controls (previous, ...

Oops! There was an error: Unable to find a solution for all the parameters needed by CountdownComponent: (?)

I'm currently working on creating a simple countdown component for my app but I keep encountering an error when I try to run it using ng serve. I would really appreciate some assistance as I am stuck. app.module.ts import { BrowserModule } from &apo ...

Having difficulty showing the successful JSON output in either the view or an alert

In my CodeIgniter project, I have three input fields named name, emp_id, and crm_id. I enter the id value and send it to the controller via AJAX and JSON to retrieve all information related to that id. The issue is that while I can see the correct output i ...

Asynchronous setTimeout for server-side operations

I am currently facing an issue with my web server. Whenever a request is made, the server initiates a phone call, waits for 3 seconds, and then checks if the call is still ongoing. I have utilized setTimeout to achieve this functionality, but it seems to b ...

jQuery function used to create an HTML menu

My goal is to dynamically update the HTML file generated by a PHP script when I modify an item in a drop-down menu using jQuery. Here is the code: JQUERY <script type="text/javascript"> $(document).ready(function() { $('#regioni&ap ...

What is the best way to combine a JSON response object with the variable J inside a for loop?

Received a JSON response as follows: { "name" : "chanchal", "login3" : "1534165718", "login7" : "1534168971", "login6" : "1534168506", "login5" : "1534166215", "login9" : "1534170027", "login2" : "1534148039", "lastname" : "khandelwal", ...

What distinguishes v-text from v-load in Vue.js when concealing {{ Mustache }}?

When experiencing the "flash of uncompiled content" in Vue, the brief moment when the page is loading and you see the {{ Mustache }} syntax, developers often use either v-text or v-cloak. According to the documentation, v-text: Updates the element’s t ...

What is the best way to identify the largest sublist within an array?

Is there a way to determine the largest sublist given this scenario? Imagine having a collection of n pixel RGB values: For example, when n = 3, pixel[1]: 255, 255, 255 pixel[2]: 0, 20, 0 pixel[3]: 5, 13, 63 The goal is to identify the largest sublist ...