Can an array be generated on-the-fly with objects contained within it?

Seeking advice on looping through an array of objects to achieve a specific result.

Here is the initial array:

var testArray = [{'name':'name1', 'xaxis':'xaxis1', 'yaxis':'yaxis1'}, 
                 {'name':'name2', 'xaxis':'xaxis2', 'yaxis':'yaxis2'}];

The length of the array may vary, but the keys remain consistent.

The desired result should be:

var resultArray = [
                   trace1 = {title: 'name1', x: 'xaxis1', y: 'yaxis1'},
                   trace2 = {title: 'name2', x: 'xaxis2', y: 'yaxis2'},
                   ];

Started by creating variable names for JSON objects like this:

for (var i = 0; i < testArray.length; ++i) {
    resultArray[i] = 'trace' + i;
}

Struggling with how to proceed in generating the JSON objects. Any advice would be appreciated.

Answer №1

Your solution using a loop to create trace objects based on testArray elements is quite clever.

However, the issue with trace1 = being incorrect JSON is something that needs to be addressed.

To fix this, you can modify the loop to construct an array of trace objects instead:
var testArray = [{'name':'name1', 'xaxis':'xaxis1', 'yaxis':'yaxis1'}, 
                 {'name':'name2', 'xaxis':'xaxis2', 'yaxis':'yaxis2'}];

var resultArray = [];
                   
for (var i = 0; i < testArray.length; ++i) {
    resultArray.push({ name: 'trace' + (i+1), title: testArray[i].name, x: testArray[i].xaxis, y: testArray[i].yaxis });
}

Answer №2

To simplify the declaration of an Array of objects, you can use the map helper function as shown below.

let id=0;
const coordinatesArray = [
  {
    'name': 'name1',
    'xaxis': 'xaxis1',
    'yaxis': 'yaxis1'
  },
  {
    'name': 'name2',
    'xaxis': 'xaxis2',
    'yaxis': 'yaxis2'
  }
].map(item => ({
  [`trace${++id}`]: {
    title: item.name,
    x: item.xaxis,
    y: item.yaxis
  }
}))

console.log(resultArray)

Answer №3

To implement this functionality, you can utilize the .map() method:

const sampleData = [{
    'type': 'type1',
    'value1': 'val1',
    'value2': 'val2'
  },
  {
    'type': 'type2',
    'value1': 'val3',
    'value2': 'val4'
  }
];

const newDataArray = sampleData.map((item, index) => ({
  [`data${index + 1}`]: {
    type: item.type,
    val1: item.value1,
    val2: item.value2
  }
}))

console.log(newDataArray)

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

Angular error ReferenceError: $Value is not defined in this context

As a newcomer to AngularJS, I am facing an issue while passing a list from the HTML file to the backend for processing. The error message ReferenceError: $Value is not defined keeps popping up. Within my controller file, I have a function named test. The ...

Challenges encountered with the "load" event handler when creating a Firefox Extension

I am currently troubleshooting a user interaction issue with my Firefox extension. The tasks that my extension needs to complete include: Checking certain structures on the currently viewed browser tab Making backend server calls Opening dialogs Redirect ...

I would appreciate it if someone could provide me with a code snippet demonstrating the process of serializing an object into JSON

I currently have a MemoryStream initialized along with a DataContractJsonSerializer object and a UserTask instance. The serializer is used to write the task object into the memory stream, which is then converted to a JSON string and encoded as ASCII. This ...

Guide on sending a JavaScript variable to PHP using AJAX

I am currently utilizing the following JavaScript code to obtain data from a td element when a button is clicked within an onclick event. function rfk(element) { var element = element.parentElement.parentElement; var id = parseInt(element.childre ...

Saving a collection of React.js components in JavaScript to a specific location or storage for future use

Important Note: I am unable to utilize the Node FS module as my knowledge about npm and fs is limited. In my current project, I am developing a simple game where users can interact by clicking a button to display an image of a 'duck' on screen. ...

utilizing AJAX to retrieve scripts from WITHIN my own domain

In the realm of ajax scripts, I encounter a scenario where referencing something within the same domain requires passing HTML and associated javascript. Due to it being a non X-domain setup, I anticipate that this could be achievable. The aim here is to fe ...

Having trouble with Vee-validate Basic example - undefined errors issue

I've been struggling to get a basic form validation page working with vee-validate. Something seems to be going wrong, but I can't pinpoint the exact issue. Why am I seeing the error: errors not defined. <!DOCTYPE html> <html> < ...

Attempting to grasp the fundamentals of angular Routing, however, upon attempting to reload the page, nothing appears to be displayed

While working in the Bracket editor, I created a file structure with various files located under the 'scripts' tags within the Index.html file. The root folder is named 'projectAngular', inside which there are subfolders like 'appC ...

Analyzing the list of paths that are passed to the function

I am looking for assistance in creating an asynchronous "getTypes" function that can analyze a list of paths and return an array describing the type of content in each path. The function should handle all cases efficiently and in case of any errors during ...

Data retrieval seems to be encountering issues in Firefox and IE9, whereas Chrome and Safari are functioning without any problems

I am using the following method function callCommentservice() { try { // Comment Service Url var getCommentServiceUrl = self.commentsServiceUrl + self.getRating + "tenantId=" + self.tenantId + "&ratedObjectTypeId=" + sel ...

Can you combine the values of a mixed data type dictionary in Python to calculate the total sum?

I have a JSON file with values in a dictionary, and I am hoping to calculate the sum of all the numeric values. However, some of the values are not numbers but different data types. My goal is to only add up the values that are numeric. {"id": &q ...

Is the final element of a multidimensional array in C sometimes unexpectedly printed by printf, based on the input?

I've been exploring the world of multidimensional arrays in C, and I'm finding myself perplexed by the unexpected behavior of printf() in the code snippet below. The purpose of this program is to initialize a 5x2 array, prompt the user for 5 int ...

Issue: "StoreController Undefined" error in Python Flask + Angular application

In the python flask application that I have built with Angular JS for the front end, there are three main files. app.py import json import flask import numpy as np app = flask.Flask(__name__) @app.route("/") def index(): ...

Animate out Material UI element with zoom effect and then remove it from the

I'm currently working on a dynamic user interface that allows for adding and removing items dynamically. Each item has both an add and remove button, with a special animation effect using Zoom. While this works smoothly when adding new items, I encoun ...

Both if and else statements are carrying out code in JavaScript/jQuery

The second if statement is functioning correctly, but the first one always triggers the else statement and never stands alone. This jQuery function is enclosed within another function that is invoked under the "$(document).ready" command. I resorted to u ...

What is the syntax for accessing a dictionary item within a <span> tag using JavaScript?

I'm working on a new functionality for a website that involves using a dictionary to store information about clubs, events, and times. var clubName = {}; var event = {}; var time = {}; var dict = new Map(); dict.set(clubName, "G ...

NodeJS not recognizing global variable causing it to return undefined

Can a global variable be defined in a node.js function? I wish to use the variable "ko" (declared in the getNumbers function) in other functions function getNumbers(callback) { result = cio.query("SELECT numbers FROM rooms WHERE durum='1'", ...

Upgrade your input button style using jQuery to swap background images

I have an input button with an initial background image. When a certain condition changes, I want to update its image using jQuery without overriding the button's global CSS in the stylesheet. Is there a way to only change the background attribute wit ...

Callback function not being triggered in Jquery's getJson method

I am currently faced with a javascript conundrum. Below is the snippet of code that I have been working on: $.get("categories/json_get_cities/" + stateId, function(result) { //code here }, 'json' ); ...

Growing Pandas Dataframe Column Using JSON Structure

I am in search of a clean and efficient method to expand a pandas dataframe column that contains a JSON object (essentially a dictionary of nested dictionaries). The objective is to create one column for each element in the JSON column in normalized form, ...