Create new object from existing object javascript

Working on JavaScript app and need help in creating a new object from response received from ajax call.

The output received is array of objects, sample format below:

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

]
}

However, my component expects JS Object in the following format:

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

Is following approach correct, please suggest better approach if any

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);

asked Mar 10, 2017 at 9:25

Create new object from existing object javascript

RohitRohit

6,66116 gold badges55 silver badges101 bronze badges

6

You could take a more functional approach with the following:

var parsed = content.items.map(function (item) {
    return {
        id: item.id,
        title: item.summary,
        start: item.start.dateTime,
        description: item.start.dateTime
    }
})

This uses the map method that is attributed with arrays to loop over each item of the array and return a new array of parsed objects.

Take a look at this fuller example.

answered Mar 10, 2017 at 9:57

Alex JonesAlex Jones

3303 silver badges14 bronze badges

1

I have another way to convert this content. Using Underscore.js to make the code more readable. Here is the example:

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);

The result as following:

[
  {
    "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": ""
  }
]

answered Mar 10, 2017 at 11:49

Create new object from existing object javascript

At the core, you are trying to 'map' from one set of data to another. Javascript's mapping function of array should be sufficient. Eg.

var content = {
  "items": [{
    "id": "02egnc0eo7qk53e9nh7igq6d48",
    "summary": "Learn to code",
    "start": {
      "dateTime": "2017-03-04T19:00:00+05:30"
    }
  }]
};

var results = content.items.map(function (item) {
  return {
    id: item.id,
    title: item.summary,
    start: item.start.dateTime,
    description: ""
  };
});

console.log(results);

answered Mar 10, 2017 at 15:38

g.suig.sui

1,3802 gold badges14 silver badges19 bronze badges

var jsonObj=[];
for (var index = 0; index < content.items.length; index++) {
  var obj = {};
  console.log(obj);
  obj["id"]=content.items[index].id;
  obj["title"]=content.items[index].summary;
  obj["start"]=content.items[index].start.dateTime;
  obj["description"]="";
  jsonObj.push(obj);
  console.log(jsonObj);
  //gcalEvents[index] = jsonObj;
}

This will give you jsonObj as your desired json object.

Hope this helps :)

answered Mar 10, 2017 at 9:40

Here's the fixed code: One error was when you've listed the content items, a "]" was missing at the end. The second one was that you were trying to assign a values to an undefined object, you first need to define the object eg: jsonObj = {}; and then do the assigning of values. I've preferred to do the object define and assigning of the values in one go.

In order to have the output as an array, you just have to define the colection as an array and not am 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);

answered Mar 10, 2017 at 9:35

2

How do you create new object in JavaScript?

Creating a JavaScript Object Create a single object, using an object literal. Create a single object, with the keyword new . Define an object constructor, and then create objects of the constructed type. Create an object using Object.create() .

How do you create a new copy of an object?

Use the Object. assign() method. Use the JSON. stringify() and JSON..
First, create a new object named person ..
Second, clone the person object using the Object. assign() method..
Third, change the first name and address information of the copiedPerson object..

Can we create object using function in JavaScript?

JavaScript has a number of predefined objects. In addition, you can create your own objects. You can create an object using an object initializer. Alternatively, you can first create a constructor function and then instantiate an object invoking that function in conjunction with the new operator.

How do I create an object in es6?

The Object() Constructor JavaScript provides a special constructor function called Object() to build the object. The new operator is used to create an instance of an object. To create an object, the new operator is followed by the constructor method. Following is the syntax for defining an object.