I am trying to solve a task here. I need to return a JSON-object to my function LearnObject - as I have understood it is an array right now. Do I have to use the JSON.stringify method to solve this? Can anybody help please?
Thank you!
var answer = "No" var mood = "I'm tired"; var answer = "No today" var mood = "Not cool at all"; var answer = "maybe" var mood = "just tired"; var answer = "yes"; var mood = "i'm ready for it"; console.log(LearnObject(answer, mood)); function LearnObject(reason,mood) { var obj =[]; var notValidAnswer = 'Try again'; var shortReason = ' Please explain your feelings in more details'; switch(answer){ case 'yes': obj.push ('Nice'); break; case 'no': obj.push ('not at all'); break; case 'maybe': obj.push ('be nicer'); break; default: obj.push(notValidAnswer); } if(validate(reason) && obj.indexOf(notValidAnswer)==-1){ obj.push(shortReason); } var objLength = obj.length; for (var i = 0; i<objLength; i++) { obj.push("Enjoy your day"); } return obj; } function validate(reason){ return reason.split('').length < 3 }
Try with JSON.parse sample code is: var obj = JSON.parse('{"var1":"Hello", "var2":"hii;"}');
document.getElementById("hi").innerHTML
= obj.var1 + " " + obj.var2;
it was hard to understand what do you want, but i think this can help you
var answer1 = "no" var mood1 = "I'm tired"; var answer2 = "No today" var mood2 = "Not cool at all"; var answer3 = "maybe" var mood3 = "just tired"; var answer4 = "yes"; var mood4 = "i'm ready for it"; console.log(LearnObject(answer1, mood1)); function LearnObject(reason,mood) { var obj = {}; var notValidAnswer = 'Try again'; var shortReason = ' Please explain your feelings in more details'; switch(reason){ case 'yes': obj['somefield'] = 'Nice'; break; case 'no': obj['somefield'] = 'not at all'; break; case 'maybe': obj['somefield'] = 'be nicer'; break; default: obj['somefield'] = notValidAnswer; } if(validate(reason) && obj.somefield;= notValidAnswer){ obj['someOtherField'] = shortReason; } obj['anotherOneField'] = "Enjoy your day" return obj. } function validate(reason){ return reason.split('').length < 3 }
Did you try JSON.stringify()? That sounds like what you need.
A great way to learn how to do things like this is to set up a sandbox somewhere and try it. This site provides such a sandbox and even has an example of stringifying an array... https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
A couple side notes on your code...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.