8

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);
Rohit
  • 6,941
  • 17
  • 58
  • 102
  • 4
    JSON is a *textual notation* for data exchange. [(More.)](http://stackoverflow.com/a/2904181/157247) If you're dealing with JavaScript source code, and not dealing with a *string*, you're not dealing with JSON. By the time you're doing the above, you're just dealing with objects, not JSON. – T.J. Crowder Mar 10 '17 at 09:27
  • Your input is an array containing two objects. The desired output you've shown is a single object. Did you mean you need an array of those? – T.J. Crowder Mar 10 '17 at 09:28
  • 2
    How do you define the title ? What should be the output ? How do you define the id ? How do you define the description ? All objects will be the same ? – Weedoze Mar 10 '17 at 09:28
  • @T The response is array of objects, I need to extract data and create new array of objects before passing to my component – Rohit Mar 10 '17 at 09:29
  • basically need to extract values from object, create new object. – Rohit Mar 10 '17 at 09:31
  • Why don't you take `jsonObj ` directly ? Why do you need it inside another object. They will be the same... – Weedoze Mar 10 '17 at 09:33

5 Answers5

13

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.

Alex Jones
  • 360
  • 3
  • 14
2

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);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

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": ""
  }
]
Crawford Wilde
  • 123
  • 1
  • 1
  • 8
2

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);
g.sui
  • 1,550
  • 3
  • 15
  • 20
1
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 :)

AKSHAY JAIN
  • 236
  • 1
  • 6
0

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);
  • 1
    You also want to explain a little what you fixed. Plus fix indentation if you want it to be (at least look like a) good answer. – dfsq Mar 10 '17 at 09:39
  • This also doesn't produce an array. The OP said (in a comment) that the result should be an array. – T.J. Crowder Mar 10 '17 at 09:44