What is the process for assigning an object or array to a different object?

I'm currently developing a function that accepts a list structured like this:

const payload = [
    [1, 2],
    [1,2,3],
    {
        name: 'sandra',
        age: 20,
        email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ec9f8d82889e8dac949596c28f8381">[email protected]</a>'
    }
]

and transforms it into an object like this:

{
  name: 'return payload',
  response: [ 
    { arr: [1, 2] }, 
    { arr: [1, 2, 3] }, 
    { arr: {
      name: 'sandra',
      age: 20,
      email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3e4d5f505a4c5f7e464744105d5153">[email protected]</a>'
    }
  ]
}

This is the current version of my function:

const returnPayload = (arr) => {
  let response = [];
    for(let i = 0; i < arr.length; i++) {
      response.push({arr: arr[i]})
    }
    return {"name": "return payload", "response": response}
}

returnPayload(payload);
console.log(returnPayload(payload))

However, when I run the function, it returns the following result:

{
  name: 'return payload',
  response: [ { arr: [Array] }, { arr: [Array] }, { arr: [Object] } ]
}

I've looked at various solutions online suggesting using JSON.stringify(obj) to tidy up the output, but I prefer a simpler and more readable alternative. With JSON method, the output looks like this:

{"name":"return payload","response":[{"arr":[1,2]},{"arr":[1,2,3]},{"arr":{"name":"sandra","age":20,"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e093818e849281a098999ace838f8d">[email protected]</a>"}}]}

Pardon the title, I'm not quite sure how to explain this issue.

Answer №1

It seems like the best solution is to iterate through the array and create an object that includes each item in the callback function:

const data = [
    [1, 2],
    [1,2,3],
    {
        name: 'sandra',
        age: 20,
        email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3340525d574152734b4a491d_57">[email protected]</a>'
    }
];

const result = {
  title: 'modified data',
  output: data.map(item => ({ content: item }))
};
console.log(result);

(note that the property name arr may not always represent an array, as shown by the third item - it might be helpful to use a more descriptive property name instead)

Answer №2

If you're looking for a way to make the output more readable, one option is to use JSON.stringify() with an extra parameter for indentation.

const data = [
    [1, 2],
    [1,2,3],
    {
        name: 'John',
        age: 30,
        email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="67140609031506271f1e1d4904080a">[email protected]</a>'
    }
]

const processPayload = (arr) => {
  let result = [];
    for(let i = 0; i < arr.length; i++) {
      result.push({data: arr[i]})
    }
    return {"label": "processed payload", "result": result}
}

processPayload(data);
console.log(JSON.stringify(processPayload(data), null, 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

Is there a glitch in the System.Json software?

Instructions for reproducing the issue: JsonPrimitive a = new JsonPrimitive("<a href=\"\"/>"); //alternatively: JsonPrimitive a = new JsonPrimitive(@"<a href=""/>"); Console.WriteLine(a.ToString()); //or Console.WriteLine((string)a); ...

Sending an array from JavaScript to PHP and then back to JavaScript

I have a task to transfer an array from one webpage to a PHP page for it to be saved in a file, and then another webpage has to retrieve that array from the file. Currently, I have an array in JavaScript containing all the necessary information: JavaScri ...

Why is my Laravel Vue CRUD not automatically updating the posts section with new data?

Hey there, I've been working on a project using Laravel 5.6 with Vue.js for CRUD functionality. I'm trying to display the posts I've just added in the posts section without having to reload the entire page. However, my current code is only s ...

Encountered an issue while attempting to handle the image uploaded via React using Node.js and Sharp

I have integrated a feature to allow users to upload their profile picture using the frontend, which is functioning properly. However, the backend keeps rejecting the uploaded image files, even if they are in jpeg, jpg, or png format. const storage = multe ...

Adjust the style of an element when hovering over a different element

Below is the HTML code in question: <div> class="module-title" <h2 class="title" style="visibility: visible;"> <span>Spantext</span> Nonspantext </h2> </div> I am looking to change th ...

Establishing a connection with mongoose within an express application

click here for an image This is the visual aid I'm referring to Any assistance with the code would be greatly appreciated. Thank you. ...

Encountering difficulties while attempting to convert JSON to XML resulting in an error being

I can't seem to figure out how to successfully convert the JSON result into XML format. I've tried the code below but it's not working as expected. Any help would be greatly appreciated. Here is the code snippet: <script src="../Jquery ...

Incorporating a CSS stylesheet into the theme settings of the Stratus 2 Beta platform

I have been attempting to personalize my Stratus 2 Beta by implementing a custom theme. I created a separate CSS file named "stratus.css" and stored it in the CSS directory of my website - with the CSS code being identical to this example. Below is my Jav ...

PHP code throwing error when trying to store JSON data in database

I'm a beginner in PHP and I'm trying to send a JSON string via POST containing an array list of products from Android to a PHP webservice. However, when I try to var_dump the decoded array, it shows null. Here is my code: <?php $servername = ...

The back-to-top feature is malfunctioning in the new Bootstrap 4 update

I've been working on adding a back-to-top button to my website using JavaScript in Bootstrap 4 with the Font Awesome icon set. It was functioning perfectly until I made some changes to the site, and now it's not working anymore. I'm pretty n ...

The function window.open when using the target '_blank' will launch a fresh browser window

I'm attempting to open a link in a new browser tab (not a new window). When I place a link on the page like this: <a href="#" onclick="window.open('http://www.google.com', '_blank');"> Click Here</a> when a user clic ...

What is the process for using AJAX and PHP to upload an image file?

I'm facing an issue where I want to insert an uploaded image into a database with user details for a profile picture. The output I receive currently shows {"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}. How can th ...

What is the best way to output multiple values within an array in programming?

Here is my code snippet: main(){ var courselist = ["dart","flutter","swift","R"]; print(courselist[0]); } I would like to print 'dart' and 'R' from the array. How can I achieve this by printing 2 or more values from an array? I attem ...

Uploading a file from a React contact form using Axios may result in S3 generating empty files

I have set up a test contact form that allows users to upload image attachments. The presignedURL AWS Lambda function is working properly After uploading, the image file (blob) appears as an image in the HTML, indicating successful addition Upon posting t ...

Service has not been properly declared

I encountered an issue with AngularJS where I am struggling to import a Service from one module to another. In the Data module, I have a Service named MenuDataService that I need to utilize in the MenuApp module. However, when attempting to do so, I receiv ...

Decode JSON in real-time on an Android device

Currently, I am utilizing the Google GSON API to parse a JSON file within my Android project. However, I am facing performance issues with the process. Below is the snippet of code that I am using for parsing the JSON data using the Google GSON API: publ ...

Comparison of WebAPI Response Codes: Understanding the Difference Between 401 and

As a part of my learning project, I am developing a WebAPI and striving to implement best practices. The initial focus is on creating an authentication API that accepts an authentication object in JSON format: { username: myusername, password: mypa ...

Guide on importing a JS file into the main JS file using Three.js

I'm fairly new to Threejs and I am trying to organize my code by putting some of my threejs code in a separate JS file and then using it in my main.js file. Here is a simplified version of what I am trying to do: main.js import * as THREE from &ap ...

When implementing the onchange function in PHP and JavaScript, the select list tends to overlook the initial value

My select list function in the code below creates a dropdown with 5 values. However, only values 2-5 work when selected, and their values are displayed on the page. Value 1 does not display no matter what I try. I have been unable to identify the issue or ...

Experiencing complications with an Angular 2 router

When a user logs into the system, they are greeted with a navigation bar featuring options like Dashboard, Customers, and Product. Below is an excerpt from my routes file: app.routing.ts export const router: Routes = [ { path: '', redir ...