Generate a dynamic JSON object using JavaScript and then deliver it back

I'm dealing with a function that is supposed to return a JSON object in this format:

this.sampleFunction = (x, filename) => {
  if (x.isPresent()) {
    return {
      'result': true
    };
  } else {
    return {
      'result': false 'value': x + "is missing in file" + filename
    };
  }
}

Additionally, I have another function that invokes the above function:

returnedResult = sampleFunction("saveButton", "AdminPage")
console.log(returnedResult)
console.log(returnedResult.result)

However, both returnedResult and returnedResult.result always end up being printed as undefined. What corrections should I make to ensure the correct JSON output?

Answer №1

You have a missing closing bracket } at this line } else, and a comma , in your return value on line 'result': false). Here is a corrected version with a working sample

Please note that I made temporary modifications to the isPresent function for it to work in this example

function isPresent(x) { return true; }

test = (x, filename) => {
  if (isPresent(x)) {
    return {
      'result': true
    };
  } else {
    return {
      'result': false,
      'value': x + " is missing in file " + filename
    };
  }
}

returnedResult = test("saveButton", "AdminPage")
console.log(returnedResult)
console.log(returnedResult.result)

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

Tips for positioning a sticky div underneath a stationary header

I'm currently utilizing Bootstrap 4 for my project, and I am encountering an issue with maintaining a div that has the class "sticky-top" just below a fixed navbar. Despite attempting to use JavaScript to replace the CSS while scrolling, it hasn' ...

Updating the background color using typescript

Before transitioning to angular development, I had experience working with vanilla Javascript. I encountered a challenge when trying to modify the css properties of specific elements using Typescript. Unfortunately, the traditional approach used in Javascr ...

The "Open in new tab" feature seems to be missing for links when using Safari on iOS

My webapp contains links structured like this: <a href="/articles/">Articles</a> I am using JavaScript to control these links within my app: $(document).on("click", 'a', function(ev) { ev.preventDefault(); ev.stopPropagat ...

Tips for adjusting the horizontal position of a grid item within a map() loop

I am trying to align the text in my Timeline component from Material Ui always towards the center of the timeline. The TimelineContent contains Paper, Typography (for title and description), and an image. Currently, I have multiple TimelineContent element ...

Ways to insert a line break using ajax

document.getElementById("msg").innerHTML += "<strike>b:</strike> "+ msgs[i].childNodes[1].firstChild.nodeValue; After retrieving the messages, I noticed that they are all displayed close to each other. Is there a way to display each message on ...

When the webpage first loads, the CSS appears to be broken, but it is quickly fixed when

Whenever I build my site for the first time, the CSS breaks initially, but strangely fixes itself when I press command + s on the code. It seems like hot reloading does the trick here. During development, I can temporarily workaround this issue by making ...

Interpolating strings in a graphQL query

Exploring the world of Gatsby and its graphQL query system for asset retrieval is a fascinating journey. I have successfully implemented a component called Image that fetches and displays images. However, I am facing a challenge in customizing the name of ...

Creating an infinite loop animation using GSAP in React results in a jarring interruption instead of a smooth and seamless transition

I'm currently developing a React project where I am aiming to implement an infinite loop animation using GSAP. The concept involves animating a series of elements from the bottom left corner to the top right corner. The idea is for the animation to sm ...

Differences between MobX local state and global state

I am currently working on a React project using mobx to manage the application state. For dump components that interact with external data sources (such as ajax calls, filtering or mapping arrays), I simply manipulate the data in those components. Howeve ...

Prevent automatic jumping to input fields

Can someone help me with a problem related to the html input tag or primefaces p:input? I am facing an issue where the cursor always automatically jumps into the input field. The height of my page is such that scrolling is required, and the input field i ...

Generated a hierarchical JSON structure from a dynamically generated form

My client has a unique page builder that allows them to create web forms using a convenient drag and drop interface. Currently, the data is output in a JSON format like this: { "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" dat ...

Implementing CSS styles with the className attribute in a Material UI component within a ReactJS application sourced from a dynamic JSON object

I have a dynamic JSON object that includes a button element. I am using createElement and Material UI to display the data from this object. I wanted to add custom CSS styling to the button component using className, but I've been struggling to achiev ...

Struggling to maintain context with axios in React despite diligent use of arrow functions

In my component, I have a function for posting data. Although it works well, the context of my component is lost in the success message. This is puzzling because I am using arrow functions. Why does the "this" context get lost in this situation? The issu ...

In JavaScript, creating a new array of objects by comparing two arrays of nested objects and selecting only the ones with different values

I've been struggling to make this work correctly. I have two arrays containing nested objects, arr1 and arr2. let arr1 =[{ id: 1, rideS: [ { id: 12, station: { id: 23, street: "A ...

Ways to bounce back from mistakes in Angular

As I prepare my Angular 5 application for production, one issue that has caught my attention is how poorly Angular handles zoned errors. Despite enabling 'production mode', it appears that Angular struggles to properly recover from these errors. ...

Restructure an array of objects into a nested object structure

I have a list of task items that I need to organize into a structured object based on the ownerID var tasks = [ {taskID: "1", title: "task1", ownerID: "100", ownerName: "John", allocation: 80}, {taskID: "2", title: "task2", ownerID: "110", ownerNam ...

Error message "Error: listen EADDRINUSE" is reported by node.js when calling child_process.fork

Whenever the 'child_process.fork('./driver')' command is executed, an error occurs: Error: listen EADDRINUSE at exports._errnoException (util.js:746:11) at Agent.Server._listen2 (net.js:1156:14) at listen (net.js:1182:10) ...

Error: The if statement is not providing a valid output

I am currently developing a basic price calculator that calculates the total area based on user input fields. While most of the program is functioning correctly, I am encountering an issue with the if statement that is supposed to determine the price rat ...

When the key code is equal to "enter" (13), the form will be submitted

When I press the Enter key, I want to submit a form if there are no error messages present. Here is the function I have created: $(targetFormID).submit(function (e) { var errorMessage = getErrorMessage(targetDiv); if (e.keyCode == 13 && errorMessa ...

Turn off self links (HAL) in Json for Spring Data Rest

I am new to using spring-data-rest. When I make a REST call in my application, I receive JSON data that includes self-links and links to related tables in the database. However, I would prefer to receive the actual JSON data instead of the links. The code ...