Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
167
rated 0 times [  170] [ 3]  / answers: 1 / hits: 18815  / 7 Years ago, fri, march 10, 2017, 12:00:00

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




More From » json

 Answers
72

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.


[#58598] Wednesday, March 8, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lizet

Total Points: 479
Total Questions: 96
Total Answers: 113

Location: Mexico
Member since Sun, Jul 25, 2021
3 Years ago
;