How can we store both a single JSON error and an array of errors in the same variable using Javascript?

My server sends me JSON with a list of errors. If there is more than one error, it looks like this:

{
    "ErrorFuncional": [
        {
            "ErrorCode": "1020",
            "ErrorReason": "xxxx",
            "ErrorPosition": "xxxx",
            "OriginalValue": "33333"
        },
        {
            "ErrorCode": "103",
            "ErrorReason": "xxxx",
            "ErrorPosition": "xxxx",
            "OriginalValue": "111"
        },
        {
            "ErrorCode": "110901",
            "ErrorReason": "xxxx",
            "ErrorPosition": "xxxx",
            "OriginalValue": "222"
        }
    ]
}

But if there is only one error, the JSON looks like this:

{
    "ErrorFuncional":
        {
            "ErrorCode": "1020",
            "ErrorReason": "xxxx",
            "ErrorPosition": "xxxx",
            "OriginalValue": "33333"
        }
}

I defined the errors variable as an array, so when trying to parse one error, an exception occurs.

Is there a way to convert a single error into an array with one element before parsing it to JSON? If not, how should I handle this scenario?

Thank you!

Answer №1

Give this a shot.

let NewErrorFunc = {
  "ErrorCode": "2020",
  "ErrorReason": "yyyy",
  "ErrorPosition": "yyyy",
  "OriginalValue": "55555"
};
    
function changeIntoArray(array)  {
  if (Array.isArray(array) === false) {
  return {NewErrorFunc: [array]};
} else {
    return {NewErrorFunc: array};
  }
}
    
console.log(changeIntoArray(NewErrorFunc))

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

"Update content dynamically with PHP-AJAX only when there are

Hey there, I've got a comment system that's being constantly updated with jQuery. My goal is to only refresh it when new records are added to the database. Is this possible? Please forgive any mistakes in my English, as I'm using Google Tra ...

Leveraging Components within Components in Vue 2

Here is the code snippet I am working with: import './menu-item'; import ItemImage from "./item-image"; Vue.component('quest-card', { props: { title: String, isFree: Boolean, points: Number, ...

What is the best way to include a dictionary within an already existing JSON dictionary in Python?

Check out this sample dictionary: It is stored in a JSON file: { "fridge": { "vegetables": { "Cucumber": 0, "Carrot": 2, "Lettuce": 5 }, "dr ...

Whenever I change the value of a textbox using plain JavaScript, the text becomes hidden from view

I'm struggling to understand why this function is making the textbox value invisible. I attempted changing the hidden field to a visible field, but that didn't solve the issue. Would appreciate some guidance. Here's the complete page code, p ...

Remove console.log and alert statements from minified files using uglifyjs-folder

Currently, I am minifying multiple files in a directory using the uglifyjs-folder feature within my npm configuration in the package.json file as shown below: "uglifyjs": "uglifyjs-folder js -eyo build/js" The process is effectively minifying all the fil ...

Infura makes ten calls to eth_getBlockByNumber for every eth_call request

Currently, I am in the process of creating a straightforward nextjs API route (https://nextjs.org/docs/api-routes/introduction) that is linked to the Ethereum blockchain for executing a view function (which doesn't require any gas) from a smart contra ...

Using jQuery to target a specific item from a retrieved list of elements

I'm currently working on a photo gallery feature that is reminiscent of Instagram or Facebook user photos. My goal is to enable users to view details about each image (such as the date) in a box that appears over the image when they hover over it. E ...

Store Dark Mode preferences in the browser's local storage using React and Material-UI

Is there a way to save the dark mode setting in localStorage? Can this approach be used for storing it? Any suggestions on how to achieve this would be appreciated. Thanks, cheers! function App() { const [darkState, setDarkState] = useState("&qu ...

An Effective Solution for Resolving the 'Use JsonReader.setLenient(true) to Accept Invalid JSON at Line 1 Column 1 Path $' Issue in Android Studio

I'm facing an issue while attempting to send a POST request to an API. The error message I receive is: To fix the problem, you can use JsonReader.setLenient(true) method in order to accept malformed JSON at line 1 column 1 path $. Is there anyone ...

Arranging JSON information based on category

I am currently populating an HTML table with data retrieved from a JSON file. It currently displays all the data in the order it appears in the JSON file, but I would like to organize it into different tables based on the "group" category in the file such ...

Connecting onClick event to a dynamically created div using Dojo

While working with dojo 1.9.2, I encountered an issue when trying to add an onClick function to a dynamically created piece of HTML code like so: clickableDiv = "<div data-dojo-attach-point=\"testBtn\">Click Me!</div>"; self.racks.in ...

The concept of immutability is crucial when utilizing a for-in loop to append an object to an array

Within my code, I have a nested loop structure consisting of a for of with a for in loop inside it. This setup retrieves information from a Neo4J database. By utilizing the Object.assign method, I am able to transfer a property from the fetched object into ...

On Internet Explorer 9, the window.open function is causing a new window to open up with

I am having an issue with redirecting my form to another page in a new window using window.open(). The problem I'm encountering is that when the new window opens, it appears blank and the original browser window redirects to the intended page for the ...

Error encountered: `unexpected token within ES6 map() function`

Do you see any issues with this code snippet? render(){ return ( var users= this.state.users.map(user => <li key={user.id}>{user.name}</li> ) <ul>{users}</ul> ) } I am receiving an error mes ...

Unconventional way of assigning class properties in Typescript (Javascript): '?='

Recently, I came across the ?= assignment expression within a class property declaration. Can anyone provide some insight into what this means? I am familiar with the new Optional Chaining feature (object?.prop), but this particular syntax is unfamiliar t ...

Cease the execution of a task in Express.js once the request timeout has been

Suppose we have the following code snippet with a timeout of 5 seconds: router.get('/timeout', async (req, res, next) => { req.setTimeout(5000, () => { res.status(503) res.send() }) while (true) { ...

Incorporate JSON data into a field with Talend Open Studio

As part of our migration process, I am working on transferring data from an old database to our new application. To achieve this, I need to extract data from the old database and create a JSON object that will be stored in a field within the new MySQL dat ...

Use Javascript to display an image based on the date, otherwise hide the div

I'm looking to implement an image change on specific dates (not days of the week, but actual calendar dates like August 18th, August 25th, September 3rd, etc). Here's the div I'm working with: <div id="matchday"> <img id="home ...

Comparing $.fn.fancybox and $.fancybox: What sets them apart?

I'd like to understand the distinction between the two items shown above. In what ways do they differ from each other? ...

I'm looking for a method to retrieve the value of an option tag and then pass it to a helper within handlebars. Can someone

Currently, I am utilizing express and handlebars in my project. I have a specific view where I aim to display certain information based on the event when a client selects an option from a select tag. However, I have some queries regarding this: Is it fea ...