Convert an array into JSON format using JavaScript

Hey there, I'm struggling with converting my function/array to JSON format. Can anyone lend a hand?

I attempted using JSON.stringify(obj) but couldn't quite get it to work. It's all a bit confusing for me at the moment.

I would be really grateful for any assistance offered.

Thanks in advance!

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 (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
}

Answer №1

Within your message, you express a desire for an object similar to the following:

 '{ "Answer" : "Try again" , "Mood" : "Enjoy your day" }'

Although converting your array directly into the desired object is not feasible, you can create a new object and utilize the values from the array. Below is the code snippet to achieve this.

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(answer3, mood3));

function LearnObject(reason, mood) {
  var arr = [];
  var jsObj = {}; 
  var notValidAnswer = 'Try again';
  var shortReason = ' Please explain your feelings in more details';

  switch (reason) {
    case 'yes':
      arr.push('Nice');
      break;
    case 'no':
      arr.push('not at all');
      break;
    case 'maybe':
      arr.push('be nicer');
      break;
    default:
      arr.push(notValidAnswer);
  }
  if (validate(reason) && arr.indexOf(notValidAnswer) == -1) {
    arr.push(shortReason);
  }
  var objLength = arr.length;
  for (var i = 0; i < objLength; i++) {
    arr.push("Enjoy your day");
  }

jsObj.Answer = arr[0];
jsObj.Mood1 = arr[1]; 

if(arr[2]){
  jsObj.Mood2 = arr[2]; 
}

if(arr[3]){
  jsObj.Mood3 = arr[3]; 
}

return JSON.stringify(jsObj);

}

function validate(reason) {
  return reason.split('').length > 3
}

To clarify my process, I started by creating an empty object named jsObj. Next, I populated that object with values from the array.

jsObj.Answer = arr[0]; signifies that the object key named "Answer" should be assigned the first value of the array. In essence,

{"answer" : first value of array}

We anticipate there will always be two items: an answer and a mood. The conditional statement checks for additional elements and appends them to the object if present.

Answer №2

When faced with a challenge, remember to always try again before giving up. As the saying goes, "Enjoy your day!"

Answer №3

var answer1 = "No";
var mood1 = "Feeling exhausted";

var answer2 = "No way"
var mood2 = "Feeling terrible";

var answer3 = "possibly"
var mood3 = "Just worn out";

var answer4 = "absolutely";
var mood4 = "I'm raring to go";


console.log(EvaluateResponse(answer1, mood1));

let [userResponse, userMood] = EvaluateResponse(answer1, mood1);
let evaluationObj = {
  uResponse : userResponse,
  uMood : userMood
}
console.log(evaluationObj)

function EvaluateResponse(reason, currentMood) {
  var result = [];
  var invalidResponse = 'Please try again';
  var briefExplanation = 'Kindly provide further details about your emotions';

  switch (answer1) {
    case 'yes':
      result.push('Great');
      break;
    case 'no':
      result.push('Absolutely not');
      break;
    case 'maybe':
      result.push('Consider being more positive');
      break;
    default:
      result.push(invalidResponse);
  }
  if (validate(reason) && result.indexOf(invalidResponse) == -1) {
    result.push(briefExplanation);
  }
  var resultLength = result.length;
  for (var i = 0; i < resultLength; i++) {
    result.push("Have a fantastic day");
  }
  return result;

}

function validate(reason) {
  return reason.split('').length < 3
}

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

Using information extracted from two separate Json files to form a Seq[Object] in Scala

I am working with a class model that looks like the following: final case class Appointment(id: Option[String] = None, service: Option[String] = None, start_at: Option[String] = None, ...

Accessing values from a JSON object in AngularJS without using a loop based on another field

Is there a way to extract the "value" associated with the "name" in JSON using Angular JS without having to iterate through the array? For instance, if I have an array like the one below with name and value fields, how can I retrieve the value "ABC" based ...

Utilizing GeoLocation in JavaScript: Implementing a Wait for $.ajax Response

Whenever I make an AJAX POST request to my backend server, I aim to include the latitude and longitude obtained from the navigator. However, it seems like the request is being sent in the background without waiting for the navigator to complete its task. ...

Determining if data from two separate lists in Vue.js matches in order to display in the template

I need to compare two sets of data - one fetched from the server and the other being default data. Data retrieved from the server: [ { "id": 7, "day": "14 April 2017", "time_list": [ { "id": 25, "time": "11:00 AM", ...

Transfer the reflectivity parameter to the JSONLoader

I'm currently working on creating a workflow in Maya for generating scenes, exporting them using the ThreeJS JSON exporter, and importing them through JSONLoader. My goal is to have the ability to include multiple objects, materials, and animations w ...

Developing recursive components in React involves creating child components that render

I am facing a simple issue where I need to create a list from JSON recursively. Here is what I have so far: const jsonMenuConfig =[ { main:"Li1", inside:[] }, { main:"Li2" ...

A simple way to add a value from a select option into a textarea when there are several dropdown menus and select elements sharing the same

I have several divs with the same class names where I need to input a value from a dropdown menu into the textarea that belongs to the div where the select element is located. I want this function to work smoothly even with more than 10 divs, which is why ...

Retrieving data from notifications without having to interact with them (using Firebase Cloud Messaging and React Native)

Currently, I am able to handle messages whether the app is open, minimized, or closed. However, how can I process a message if a user logs into the application without receiving a notification? useEffect(() => { messaging().setBackgroundMessageHa ...

When attempting to dispatch in getServerSideProps, the State refuses to change. Could it be due to the Redux-Next-Wrapper?

I'm facing an issue where the Redux Store does not change when I dispatch in getServerSideProps. Even though I can see the changes in console log after dispatch, the store appears as an empty array when the page loads. Why are these changes not taking ...

Optimal approach for managing exceptions when working with Q.promise

The method below is used to extract an ID from a given object: module.exports.getId = function(someObject) { var myId = null; return Q.Promise(function(resolve, reject, notify) { // Loop through all the id's someObject.user ...

Changing the color of dots in a React Material-UI timeline

Hey there, I'm trying to change the default color of the MUI TimelineDot component. I attempted to do so by adding this code: <TimelineDot sx={{ '& .MuiTimelineDot-root': { backgroundColor: '#00FF00' }, }} /> Unfortunate ...

Can you suggest a method using Lodash to remove specific rows from an array based on the value of a certain field within the array?

Currently, I am utilizing the following function: remove: function (arr, property, num) { for (var i in arr) { if (arr[i][property] == num) arr.splice(i, 1); } }, Although this functi ...

Is there a way for me to manipulate the RGB values of the canvas in such a manner that the Red and Green components of the gradient are determined by dividing the position of my mouse cursor

My homework assignment requires using RGB colors where the red value is set to 0, green is the x-coordinate divided by 2, and blue is the y-coordinate divided by 2. I've been trying to control the colors on a canvas using addColorStop functions, but I ...

Having trouble activating the submit function using an external JavaScript file

Having trouble getting the form to submit properly. I have placed the form inside a <div id="access"></div> by setting its innerHTML using an included js file in the header of the page. Here's how it looks: <div id="access"> < ...

Ensure that when you click on the next dropdown menu opener button, the previous dropdown menu closes and only the new menu remains open

Take a look at this page first to get an understanding: On this page, I have implemented multiple dropdown menus that should open when clicked on their respective opener buttons (3 bar icon) and close either when clicked again or anywhere else on the page ...

Invoke a method within an *ngIf statement in Angular 5

Suppose I have the following code snippet: <div *ngIf="item">lorem ipsum</div> Is there a way to trigger a function if the *ngIf condition is true? Perhaps something like this... <div *ngIf="(item) : callFunction() ? ...">lorem ipsum& ...

Error: Vuex commit fails due to JSON circular structure issue

Using Vue.js along with the vuex store, I make an API call to validate an item, which returns arrays of errors and warnings. Below is my vuex action : export function validateitemReview ({ commit, dispatch, state }, { reviewId, type, itemreviewData }) { ...

Make sure to include the onBlur and sx props when passing them through the slotsProp of the MUI DatePicker

This DatePicker component is using MUI DatePicker v6. /* eslint-disable no-unused-vars */ // @ts-nocheck import * as React from 'react'; import { Controller } from 'react-hook-form'; import TextField from '@mui/material/TextField&a ...

Modify the class's height by utilizing props

Using Vue 3 and Bootstrap 5, I have a props named number which should receive integers from 1 to 10. My goal is to incorporate the number in my CSS scrollbar class, but so far it's not working as expected. There are no error messages, it just doesn&a ...

Working with JSON arrays in Watson Assistant: add and edit functionality

Currently, I am delving into the world of Watson AI/Assistant in order to incorporate it into our services as a web development firm. To enhance my understanding of the assistant, I have embarked on a self-taught journey by creating a text-based adventure ...