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

Tips on sending form data, including a file, to Ajax using the onclick() method

My Modal Includes a Form: <div class="modal fade bs-example-modal-lg" id="myMODALTWO" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" id="form-content"> <div class="modal-dialog modal-lg" role="document"> ...

It seems that there is a null value being returned in the midst of the

I have developed a model using express. While setting this in one function, it returns null in another function, forcing me to use return. What is the proper method to handle this situation? const Seat = function(seat) { this.seat = seat.seat; this. ...

Utilizing several carets in a single or multiple text areas and input boxes

Just a quick question... Can a textbox have two carets simultaneously, or can we have two separate textboxes both focused at the same time? I am aware of simulating this using keydown listeners but I'm specifically looking for visible carets in both ...

Transmitting unique characters, such as a caron symbol, via xmlhttp.responseText and encoding them with json_encode

I am struggling to retrieve data from a database that contains a special character (caron) and then pass it through xmlhttp.responseText using json_encode to fill textboxes. However, the textbox linked to the data with the special character (caron) is not ...

Utilizing VueJS and Lodash: The technique for extracting an array of objects exclusively featuring a specific key string

I am attempting to extract certain data from an Object that has a string _new attached to it. Explore the code on Codesandbox: https://codesandbox.io/s/vibrant-bardeen-77so1u?file=/src/components/Lodash.vue:0-353 This is what my data looks like: data.j ...

Automatically press a button that appears on the webpage

I am looking to automate the clicking of a button that appears on a website. How can I accomplish this using Python? I have no experience in JavaScript and am fairly new to programming. Here is the outer HTML code for the button: <button type="button" ...

Tips for enforcing validation rules at the class level using Angular's version of jQuery Validate

After utilizing jQuery Validate's convenient addClassRules function to impose a rule on all elements of a specific class, rather than relying on the attributes of their name, I encountered a roadblock when trying to do the same with the Angular wrappe ...

Confirm that the method has been called by utilizing the AVA testing framework

As I work on creating a unit test for my React component using tools like Ava and Enzyme, I encounter an issue. My goal is to create a simple unit test that checks if a certain method has been called. The test should pass if the method has indeed been call ...

Combining various array values into a single key in JSON格式

Issue: I am working on a sign-up form for new users using HTML. The goal is to store multiple arrays (each containing "username: username, password: password, topScore: 0) within one JSON key ("user" key). However, the current functionality only allows f ...

NodeAutoComplete: Enhanced Autocompletion for Node.js

I am attempting to utilize autocompletion of a JavaScript file with Node.js and Tern. However, the documentation for Ternjs is incredibly lacking. const tern = require("tern"); const ternServer = new tern.Server({}); const requestDetails = { "qu ...

What is the reason for labels appearing inside select boxes?

Can someone help me understand why my select box label is displaying inside the select box? For example, when I am not using react-material-validator it looks like this: https://codesandbox.io/s/5vr4xp8854 When I try to validate my select box using the r ...

What is the most effective method for populating data within a browser window?

I have a list of files stored in $scope.data that I retrieved from the searchFactory. Now, my goal is to display these files in the browser window. How can I accomplish this task? ctrl.js $scope.displayFiles = function (){ $window.open($scope.dat ...

REST and using a passed authentication token

As I embark on my first journey into REST programming, I find myself grappling with the challenge of passing the session token. Despite scouring various forums for similar issues, I have yet to find a solution. Here is a snippet of Ruby code that I am cur ...

How can we dynamically create paths in Swagger-php?

I'm currently utilizing Swagger for documentation purposes and have found success in generating a JSON file from annotations. However, I am now looking to programmatically add additional paths to the generated JSON file. Upon further exploration, I c ...

The d3 hierarchy possesses the capability to compute the average values of child nodes

Looking for a solution with d3 visualization that involves averaging up the value of score on the lowest nodes and dynamically adding that average to the parent node above. It seems like there isn't an easy method in d3 for this task. The desired outc ...

Updating nested interface values using React hooks

I am looking to develop an application that can seamlessly update a nested configuration file after it has been imported (similar to swagger). To achieve this, I first created a JSON configuration file and then generated corresponding interfaces using the ...

Hiding a specific tag with vanilla JavaScript based on its content

I am facing a challenge with my code that is supposed to hide div elements containing a specific word along with additional text. I have tried multiple solutions but none seem to work effectively. Any assistance on how to hide divs properly will be greatl ...

What is the best way to implement a composite primary key in DocumentClient.batchWrite()?

I am attempting to conduct a batch delete process based on the instructions provided in this documentation. The example given is as follows: var params = { RequestItems: { /* required */ '<TableName>': [ { DeleteRequest: ...

Refresh two angular-datatables

I'm facing a challenge when it comes to updating two datatables simultaneously on the same page. Here's how my HTML is structured: <table id="datatable1" ng-if="Ctrl.dtOptions1" datatable="" dt-options="Ctrl.dtOptions1" dt-column-defs="Ctrl. ...

The successful execution of $.ajax does not occur

Starting out with ajax, I wanted to create a simple add operation. Here is the code that I came up with: HTML: <!doctype html> <html> <head> <title>Add two numbers</title> <meta content="text/html;charset=utf-8" h ...