What is the best way to generate a fresh object using an existing object in Javascript?

Struggling with generating a new object from the response obtained from an ajax call in JavaScript app.

The data received is an array of objects, shown below:

{
  "items": [
    {
      "id": "02egnc0eo7qk53e9nh7igq6d48",
      "summary": "Learn to swim",
      "start": {
        "dateTime": "2017-03-04T19:00:00+05:30"
      }
    }        

]
}

However, my component requires JS Object in this format:

{
id: "e1",
title: "Express",
start: "Jan 13, 2010",
description: "Jan 13, 2010"
}

Wondering if the current approach is correct, open to better suggestions

var content = {
    "items": [{
        "id": "02egnc0eo7qk53e9nh7igq6d48",
        "summary": "Learn to code",
        "start": {
          "dateTime": "2017-03-04T19:00:00+05:30"
        }
      }
      }
    };
    var gcalEvents = {};
    var jsonObj = {
      "id": "e1",
      "title": "Oracle Application Express",
      "start": "Jan 13, 2010",
      "description": "Jan 13, 2010"
    };

    console.log(content.items.length);
    for (var index = 0; index < content.items.length; index++) {
      var obj = content.items;
      console.log(obj);

      jsonObj.id = obj[index]["id"];
      jsonObj.title = obj[index].summary;
      jsonObj.start = obj[index].start.dateTime;
      jsonObj.description = "";
      console.log(jsonObj);
      gcalEvents[index] = jsonObj;
    }
    console.log(gcalEvents);

Answer №1

If you want to adopt a more functional approach, consider the code snippet below:

var processed = data.records.map(function (record) {
    return {
        id: record.id,
        name: record.title,
        timestamp: record.timestamp
    }
})

This code snippet utilizes the map method which iterates over each item in an array and generates a new array containing modified objects.

For a more comprehensive example, check out this detailed demo.

Answer №2

I have figured out another method to transform this data with ease. Utilizing Underscore.js for better code readability. Here's an illustration:

var content = {
    "items": [{
        "id": "02egnc0eo7qk53e9nh7igq6d48",
        "summary": "Learn to code",
        "start": {
            "dateTime": "2017-03-04T19:00:00+05:30"
        }
    }, {
        "id": "nj4h567r617n4vd4kq98qfjrek",
        "summary": "Modern Data Architectures for Business Insights at Scale Confirmation",
        "start": {
            "dateTime": "2017-03-07T11:30:00+05:30"
        }
    }]
};
var result = _.map(content.items, function(item) {
    return {
        id: item.id,
        title: item.summary,
        start: item.start.dateTime,
        description: ""
    };
});
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

The outcome is as shown below:

[
  {
    "id": "02egnc0eo7qk53e9nh7igq6d48",
    "title": "Learn to code",
    "start": "2017-03-04T19:00:00+05:30",
    "description": ""
  },
  {
    "id": "nj4h567r617n4vd4kq98qfjrek",
    "title": "Modern Data Architectures for Business Insights at Scale Confirmation",
    "start": "2017-03-07T11:30:00+05:30",
    "description": ""
  }
]

Answer №3

Essentially, your goal is to transform data from one set to another. The mapping function in JavaScript can be a powerful tool for this task. For example:

var data = {
  "elements": [{
    "id": "02egnc0eo7qk53e9nh7igq6d48",
    "name": "Master JavaScript",
    "date": {
      "dateTime": "2017-03-04T19:00:00+05:30"
    }
  }]
};

var newData = data.elements.map(function (element) {
  return {
    id: element.id,
    title: element.name,
    dateTime: element.date.dateTime,
    description: ""
  };
});

console.log(newData);

Answer №4

let dataObj = [];
for (let i = 0; i < itemsList.length; i++) {
  let item = {};
  console.log(item);
  item["id"] = itemsList[i].id;
  item["title"] = itemsList[i].summary;
  item["start"] = itemsList[i].start.dateTime;
  item["description"] = "";
  dataObj.push(item);
  console.log(dataObj);
  //calendarEvents[i] = dataObj;
}

This code snippet generates the desired json object named dataObj.

I hope you find this information helpful :)

Answer №5

After making the necessary corrections, here is the updated code snippet: One issue was identified when listing the content items - a "]" was missing at the end. Another mistake was attempting to assign values to an undefined object. To resolve this, it is crucial to first define the object eg: jsonObj = {};, and then proceed with assigning the values. Personally, I find it more efficient to define the object and assign values in one go.

To ensure that the output is in array format, simply define the collection as an array rather than an object eg: var gcalEvents = []

var content = {
  "items": [
    {
      "id": "02egnc0eo7qk53e9nh7igq6d48",
      "summary": "Learn to code",
      "start": {
        "dateTime": "2017-03-04T19:00:00+05:30"
      }
    },
    {
      "id": "nj4h567r617n4vd4kq98qfjrek",
      "summary": "Modern Data Architectures for Business Insights at Scale Confirmation",
      "start": {
        "dateTime": "2017-03-07T11:30:00+05:30"
      }
    }
  ]
};
              var gcalEvents = [];
                var jsonObj = {
                    "id": "e1",
                    "title": "Oracle Application Express",
                    "start": "Jan 13, 2010",
                    "description": "Jan 13, 2010"
                };
                
                //console.log(content.items.length);
                for(var index=0; index < content.items.length; index++){                    
                    var obj = content.items[index];
                    //console.log(obj);
                    
                    jsonObj = {
                      'id': obj["id"],
                      'title': obj.summary,
                      'start': obj.start.dateTime,
                      'description': ""   
                    }
                    //console.log(jsonObj);
                    gcalEvents[index] = jsonObj;
                }
                console.log(gcalEvents);

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

Leverage the package.json script without relying on any yarn/npm commands

Can scripts commands be executed within the package.json file without needing to include yarn or npm? For example: "scripts": { "get": "node index.js" } Currently, in order to run this script I have to use yarn get [ar ...

Generating a dynamic JSON tree from a database using Java

I have a table stored in the database with the following structure and data: https://i.stack.imgur.com/Lmy9D.png I am looking to extract the JSON tree data from this table using Java: [ { "id":"null", "text":"Text1", "ch ...

Incorporate the xml2js JavaScript library with Angular 2 for enhanced functionality

I've been attempting to utilize xml2js as an XML parser within my Angular 2 (RC 1 with TypeScript) web application. Unfortunately, I've encountered several errors without finding a solution that works. Here is the detailed process I followed: ...

Enhancing Efficiency and Optimization with jQuery

Recently delving into the world of jQuery, I have been on the lookout for ways to enhance the speed and performance of my code. If anyone has any tips or valuable resources that could aid me in this endeavor, I would greatly appreciate it. Thank you, Bev ...

Unable to locate properties "offsetHeight" or "clientHeight" within a React/Next.js project developed in TypeScript

I have a unique customized collapsible FAQ feature that adjusts its height based on whether it's expanded or collapsed. import { useState, useRef, useEffect } from "react"; export default FAQItem({title, description}: FAQItemProps) { cons ...

The "self" variable in the Node.js prototype object fails to retain the correct context for the callback function

Although I have experience as a developer, I am new to Java Script and Node.js. I have searched through various examples and Stack Overflow answers, but I couldn't find a simple and complete example of a prototypical class with correct 'self&apos ...

Tips for keeping a JSON file intact while transitioning from localhost to a server

I've successfully been able to access a .json file on my localhost, but now I need to deploy and localhost won't be available. Here's a snippet of the code: // BurgerForm.vue methods: { async getIngredients() { const req = await fet ...

What might be causing my mongoose query to take so long? (~30 seconds)

I've encountered a problem with a route in my application. This specific route is supposed to fetch an array of offers that a user has created on the app by providing the user's id. Initially, when the user has only a few offers, the query execut ...

When making an Ajax request to a controller, rather than simply returning JSON data, it redirects you to a

Utilizing jQuery and MVC 5, I have implemented a modal form in my project. Upon clicking 'ok' on the modal box, the javascript function should trigger an ajax call to the "Companies/Createa" controller. The code successfully executes and update ...

What is the best way to interpret this JSON data?

When receiving data from an ASP.Net webservice, I am presented with the following JSON string: {"d":{"Table":[{"col1":123,"col2":"name","col3":"name","col4":100,"col5":"\/Date(1153033200000)\/"},{"col1":123,"col2":"name","col3":"name","col4":101 ...

Using classic ASP to populate a JavaScript array from a VBScript drop-down menu

To create a JavaScript array based on the selected values from multiple drop down lists, each with the same name due to being generated in a for loop, the following code snippet is currently being used: <script language="JavaScript"> var array ...

Is there a way to remove a dynamically rendered component from a list?

Whenever I click a button, the same component is dynamically rendered on top of the list. But now, I need to implement a feature where users can delete any component from the list by clicking a cancel button associated with each component. Here's my ...

Trigger an Event Handler only after ensuring the completion of the previous event handling

When attaching an event handler to a callback, it is important to consider the timing of the actions. For example: $("someSelector").on('click',callBackHandler); function callBackHandler(){ //Some code $.ajax({ //Ajax call with succe ...

There was an issue with the origin null not being permitted by Access-Control-Allow-Origin

Possible Duplicate: XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-Origin I am currently working on a weather application that runs smoothly in browsers. However, when I try to deploy it on my Android phone, it encounters iss ...

What could be the reason for the malfunctioning transition effect in my slider animation?

Having trouble getting my slider animation to work. I've tried different CSS styles but the slide transition is not functioning as expected. When one of the buttons is clicked, I want the slide to change from right to left or left to right. Can anyone ...

How can I pass standard HTML as a component in React?

I need help creating a Higher Order Component (HOC) that accepts a wrapper component, but allows me to pass standard HTML elements as inner content. Here is an example of what I want to achieve: type TextLike = string | {type,content} const TextLikeRender ...

Refresh Angular controller after ng-click event is triggered

In my current setup, I have a controller that consists of one main object containing various functions. Initially, default values for variables are set and the init() function is used to fetch data from the database. Everything on the page seems to be fu ...

FullCalendar Not Responding to JSON Parsing

Here is how my FullCalendar jQuery code is set up: $(document).ready(function () { $('#calendar').fullCalendar({ events: { url: '/admin/index.php', type: 'GET', data: { m: '1&apo ...

Securing the connection between clients and servers through encryption

For my mobile client, I am using Xamarin, with node.js as my backend and MongoDB as the database. The main issue I am facing is how to securely store user data in the database. If I only do server-side encryption, there is a risk of hackers intercepting th ...

Perform the action: insert a new item into an array belonging to a model

Here is the structure of my model: var userSchema = new mongoose.Schema( { userName: {type: String, required: true}, firstName: {type: String}, lastName: {type: String}, password: {type: String, required: true}, ...