What is the best way to add an array to my JSON object in Javascript?

I'm currently in the process of formatting an array into a JSON object for API submission.

Struggling to find the right method to transform my array into the desired structure.

This is what my array looks like:

data: [
    ["Lisa", "Heinz", "1993-04-15" ],
    ["Bob", "Dylan", "1998-09-12"],
    ["Cabbage", "Man", "1990-01-11"],
    ["", "", ""]
  ]

What I want it to look like as a JSON object:

{person:[{"name":"Lisa","last_name":"Heinz","dob":"1993-04-15"},{"name":"Bob","last_name":"Dylan","dob":"1998-09-12"},{"name":"Cabbage","last_name":"Man","dob":"1990-01-11"},{"name":"","last_name":"","dob":""}],"object_id":259,"test":"bob","attribute":"bob123"}

Here's my current approach:

let json = {}
for (let person of formData) {
    const identifier = `person${formData.indexOf(person)}`;
    json[identifier] = { 
        name: person[0],
        last_name: person[1],
        dob: person[2]
    }
}
json.object_id = "259";
json.wp_test = "bob";
json.attribute = "bob123";

The output resembles this:

{"person0":{"name":"Lisa","last_name":"Heinz","dob":"1993-04-15"},"person1":{"name":"Bob","last_name":"Dylan","dob":"1998-09-12"},"person2":{"name":"Cabbage","last_name":"Man","dob":"1990-01-11"},"person3":{"name":"","last_name":"","dob":""},"object_id":259,"wp_test":"bob","attribute":"bob123"}

Experimented with various approaches but haven't found the ideal solution yet - would appreciate a straightforward method to achieve the desired shape.

Answer №1

Ensuring the proper alignment of keys and indexes is essential.

var data = [
  ["Alice", "Smith", "1993-04-15"],
  ["John", "Doe", "1998-09-12"],
  ["Carrot", "Woman", "1990-01-11"],
  ["", "", ""]
]

var individuals = data.reduce(function(aggregate, item) {
  aggregate.push({
    first_name: item[0],
    last_name: item[1],
    dob: item[2],
  })
  return aggregate;
}, [])

var result = {
  people: individuals,
  ID: 259,
  test_field: 'example',
  details: 'sample123',
}

console.log(result)
.as-console-wrapper {max-height: 100% !important}

Answer №2

To achieve this task, you can iterate through the input array using the Array.map() method.

Check out the demonstration below:

const data = [
  ["Lisa", "Heinz", "1993-04-15" ],
  ["Bob", "Dylan", "1998-09-12"],
  ["Cabbage", "Man", "1990-01-11"],
  ["", "", ""]
];

const jsonObj = {};

jsonObj.person = data.map(arr => ({ name: arr[0], last_name: arr[1], dob: arr[2] }));

jsonObj.object_id = "259";
jsonObj.wp_test = "bob";
jsonObj.attribute = "bob123";

console.log(jsonObj);

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

Combining Nested Objects in MongoDB

I have searched extensively for a solution but I am struggling to find a resolution to my issue. I have two MongoDB (Node.JS) collections: user & statistics. My goal is to merge the results using aggregate. Below are the structures of the collection ...

Ignoring capitalization, search for occurrences in a jq document

Is there a case-insensitive matching support in JQ? Here is the filter in question: .user | contains("thinking") Along with the JSON data: { "id": "1338268256814161923", "user": "Thinking of going through t ...

populating a HTML image tag 'src' attribute with data extracted from API javascript code

Hey there! I'm currently working on integrating an image element from the openweatherAPI that corresponds to the weather icon retrieved from the JSON data when a user inputs a city. This means displaying images like scattered clouds or clear skies bas ...

Angular encountered an error when trying to access the property "fruits" of an undefined object

When working with Angular, I encountered an issue where I received the error message "cannot read property 'fruits' of undefined." Within my class definition, I have included the following: export class MyClass implements OnInit { fruits: any[] ...

Convert stylish row into JSON

Querying Dapper Results I am facing an issue with storing a Dapper Row as a JSON string in our database. Despite several attempts, I have not been successful in achieving this. Let me provide some context on the matter. Project Details In our current pr ...

Storing dataset characteristics in a JSON file utilizing Vue.js form response

I am currently working on creating a JSON file to store all the answers obtained from a Form. Some of the input fields have an additional dataset attribute (data-tag). When saving the Form, I aim to extract these 'tags' and include them in the JS ...

What is the process for incorporating items from Slick Grid into a Multi Select TextBox?

Exploring the world of Slick Grid for the first time. Here is where I define my variables in JavaScript. var grid; var printPlugin; var dataView; var data = []; var selectdItems = []; var columns = [ { id: "Id", name: "Id", field: "Id", sortable: t ...

Why is the leading zero being ignored when I try to print the contents of the session in PHP?

Encountering an issue with printing the content session. The problem arises when creating the session, as the variable is initially in string format (varchar obtained from a mysql field): Initial variable: 09680040 Printed with alert or displayed in div: ...

JavaScript - Deleting the last element of an array

I have currently integrated a third-party API to visualize data using Highcharts. This external API provides data specific to the current month, such as March, April, May, and so on. graphArrOne contains an array with 251 elements. graphArrTwo contains ...

Modifying browser.location.href Cancels AJAX Requests

I am facing an issue with my HTML page. I have a button that, when clicked by the user, updates the window.location.href to the URL of a text file. In order to ensure that the file is downloaded and not opened in the browser, the text file is served with C ...

We have encountered an issue with the syntax in the code: ajaxsample/update_agenda. It seems to be an unrecognized expression according to

Here's the code for updating my controller: public function update_agenda() { $id= $this->input->post('did'); $this->load->model('agenda_model'); $data = array ( ...

Generate a multidimensional array based on data retrieved from a database table

I have a database table in MySQL with the following structure: folder_id (int(11), auto increment) folder_name (varchar) folder_class(varchar) folder_link (varchar) My goal is to loop through this table and store each row like this: $packs = array( ...

WebView no longer refreshes when the document location is updated

I currently have a basic HTML/JavaScript application (without Phonegap) that I utilize alongside a native Android app and a WebView. When certain situations arise, I need to reload the current page in the JavaScript portion. On my old phone with Android 4 ...

Error in Angular 2: The app.component.html file triggered an exception at line 1, character 108 due to excessive recursion

After successfully setting up the Angular 2 quickstart and connecting to an express server, I encountered a problem when switching from using the template property to component templateUrl. I have created a Plunker to showcase this issue: Plunker Demo imp ...

Using .done(), .then(), and .when() in jQuery for sequencing ajax requests in a specific order

After diving into the world of Promises in jquery and trying to avoid "callback hell" when dealing with multiple ajax requests, I still find myself without a clear answer on which method to use - whether it's .done(), .then(), or .when() - for chainin ...

Transforming PHP shortcode into JQuery functionality

My website is built on Wordpress, and I use javascript to load some of the content. Here's an example: jQuery(".portfolio-fs-slides").css({"display":"none"}).prepend('<div class="portfolio-fs-slide current-slide portfolio-ppreview"><d ...

Responsive design involves ensuring that web elements such as divs are properly aligned

I am currently working on aligning 2 divs in a specific way that is responsive. I would like the right div to stack on top of the left div when the screen width reaches a certain point, as opposed to them both taking up 50% of the container's width. ...

Is it possible to delete browsing history in Express using node.js?

Upon user login, I store user information in browser sessions on the client side (using Angular) like this: $window.sessionStorage.setItem('loggedInUser', JSON.stringify(val)); For logout authentication on the backend (using Passportjs), I have ...

"The `Head.js` method called `.js()` allows for dynamic

Recently, I came across some code that was passed down to me from work, and it involves making an api call using head.js: head.js( { 'application' : 'someurl.com/foo.js' }); I'm curious if this actually registers the javascript a ...

Tips for moving a texture horizontally across a sphere using threejs

I have a 360 degree viewer tool. Is there a way to load a texture in a specific position that will rotate the original image by a certain number of degrees or units around the Y-axis without altering anything else about how the picture is displayed? If s ...