What is the best way to structure a JSON object with keys that can change dynamically?

  var data= [{_id: "5a93cbd49ae761a4015f6346", nombre: "Chicago - Missouri", longitud: "-94.6807924", latitud: "38.287606"},
{ _id: "5a93ca539ae761a4015f6344", nombre: "Boston - Central Falss", longitud: "-71.4111895", latitud: "41.8902971"},
 { _id: "5a93ccbf9ae761a4015f6349", nombre: "Houston - Dallas", longitud: "-97.0117365", latitud: "32.8209296"}]

var d=[];
for(var i in data){
    d.push({ data[i].nombre:data[i]["_id"] })
}

I want to create a JSON object with the following structure:

{ "nombre":"_id" }

For instance:

 { "Chicago - Missouri":"5a93cbd49ae761a4015f6346"}
 { "Boston - Central Falss- Missouri": "5a93ca539ae761a4015f6344" }4

Where did I go wrong?

Thank you

Answer №1

Give this a shot -

let info = [{_id: "5a93cbd49ae761a4015f6346", name: "Chicago - Missouri", longitude: "-94.6807924", latitude: "38.287606"},
{ _id: "5a93ca539ae761a4015f6344", name: "Boston - Central Falls", longitude: "-71.4111895", latitude: "41.8902971"},
{ _id: "5a93ccbf9ae761a4015f6349", name: "Houston - Dallas", longitude: "-97.0117365", latitude: "32.8209296"}]

let newData = [];
for(let index in info){
    let pushObject = {};
    pushObject[info[index].name] = info[index]["_id"];
    newData.push(pushObject);
}
console.log(newData);

Answer №2

Start by creating an object, adding the necessary data, and then push it into the array d

var data= [{
  _id: "5a93cbd49ae761a4015f6346",
  name: "Chicago - Missouri", 
  longitude: "-94.6807924", 
  latitude: "38.287606"
},{ 
  _id: "5a93ca539ae761a4015f6344", 
  name: "Boston - Central Falls", 
  longitude: "-71.4111895", 
  latitude: "41.8902971"
},{ 
  _id: "5a93ccbf9ae761a4015f6349", 
  name: "Houston - Dallas", 
  longitude: "-97.0117365", 
  latitude: "32.8209296"
}]

var d=[];
for(var i in data){
    var temp = {};
    temp[ data[i].name ] = data[i]["_id"];
    d.push(temp)
}

console.log(d);

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

Title Tooltip Capitalization in Vue.js: A Guide

Is there a way to change only the first letter of the title tooltip (from a span) to be capitalized? I attempted using CSS with text-transform: capitalize;, however, it didn't have the desired effect. <template lang="pug"> .cell-au ...

JavaScript function to toggle the visibility of navigation with a click of a button

I'm attempting to create a functionality in my code where the Open navigation button hides when the side navigation opens upon clicking. The desired behavior is for the openNav button to be hidden when it's clicked and then shown again when close ...

Is client-side JavaScript executed prior to server-side JavaScript in AJAX?

I'm curious about how client-side code interacts with server-side responses. I have a lengthy and complex piece of code that triggers a function which in turn executes some server-side code using a HTTPRequest Object, returning a string to the calling ...

Modify the data displayed on the chart by choosing the desired year from the dropdown options

In my Angular app, I am showcasing a chart that visualizes data based on selected starting and ending years from dropdown menus. The X axis represents 18 cities, while the Y axis displays "IAP" values. To calculate the "IAP" values for each city within the ...

What could be causing the lack of animation in W3schools icons?

I've followed the steps provided and even attempted to copy and paste them. However, I'm experiencing an issue where the animation doesn't fully execute. Instead of the bars turning into an X shape, they reset halfway through the animation. ...

The VueJS app seems to be experiencing difficulties with rendering the content

Just starting out with VueJS and I have my initial files - index.html and index.js. I want to stick with just these two files and not add any more. Here's the content of index.html: <html lang="en"> <head> <meta charset ...

Tips for managing post-generated buttons using jQuery?

I've created buttons using JavaScript and added them to my HTML. Now I want to use jQuery to handle the clicks on b_1 and b_2. How can I make this work? $("#mainbutton").click(function (){ document.getElementById("content").innerHTML = '< ...

Trigger the callback function once the datatables DOM element has finished loading entirely

Hello there! I have a question regarding datatables. Is there any callback function available that is triggered after the datatables DOM element has finished loading? I am aware of the callbacks fnInitComplete, but they do not serve my purpose. Specificall ...

Is your Ajax response suddenly failing to work after the initial attempt?

Describing my predicament: The code snippet below is what I have been using to insert a custom-designed div into my webpage. Initially, the div is successfully added; however, it stops working after the first instance. $('#addanother').click(fu ...

How can I receive user input in JavaScript while incorporating three.js?

I am currently exploring the functionalities of this three.js example () and I am interested in enabling users to input specified X, Y, and Z positions for boxes dynamically. Initially, I considered utilizing a JavaScript prompt like below: var boxes = p ...

An error occurred while trying to load the XMLHttpRequest due to a NetworkError that was

I have encountered an issue while working on a client-side project using jQuery, JavaScript, and various jQuery plugins. Our professor supplied us with a proxy.php file to fetch the required data for our web application. I incorporated the easy tab plugin ...

concerns regarding the security of JSON parsing

Is there a potential security vulnerability when using JSON.parse() on data from an untrusted or malicious source? Are there inherent risks in the JSON.parse() function itself when handling such data? Please note that I am not referring to: Specific att ...

The Select2 ajax process runs twice

I am encountering an issue with a script I have that retrieves data from the backend to populate a select2 dropdown. The problem is that the ajax call is being triggered twice every time, which is not the desired behavior. I'm unsure of what mistake I ...

Having difficulty controlling the DOM using cheerio in a Node.js environment

I am currently working on a basic program using Node for the server side with cheerio. Here are the code snippets provided: Server Side: /** * Module dependencies. */ var express = require('express') , routes = require('./routes') ...

Use radio buttons to enable switching between different data options within a dropdown menu

I am working on a dropdown box that is populated dynamically using JSON data. The content in the dropdown can be categorized into 4 types, so I have included radio buttons to switch between these categories. I have created HTML code to toggle between manu ...

Efficiently handling jsonwebtoken errors in node and express

Here is the verification function I've created: exports.verifyToken = function(req, res, next){ var token = req.body.token; jwt.verify(token, config.sessionSecret, function(err, decoded) { if(err){ return next(err); }else{ ...

Error encountered: unable to locate module - '@deck.gl/exper-layers'

When attempting to run npm start on the trip example in deck.gl, I encountered an issue. Although other examples open without any problems, the trip example is giving me this npm error: Module not found: Error: Can't resolve '@deck.gl/experim ...

Is there a way to run only one instance of puppeteer.launch() and simply forward pages to it in Node.js?

I have a concern regarding the code snippet below. It appears to be launching the browser on every request, potentially causing server issues on Heroku. I would like to modify it so that puppeteer is launched as a Singleton instance, where it only needs ...

JQuery Ajax: The loaded content flickers into view, revealing old content momentarily

Having an issue with my ajax code. I am working on a project that involves some links and a content area. The idea is that when a user clicks on a link, the content area should be hidden, load new data, and then show the updated content. However, I have no ...

Transfer files with Ajax without the need for a form tag or submission

I'm trying to send images via AJAX without submitting a form. Normally, when submitting a form I can access the images using $_FILES['images']['tmp_name']; However, when trying to send files, I receive an object FileList in an arra ...