Formatting Arrays of Objects

Looking to reformat an object in this structure:

 var data =  {
      "student": [
        [
          "name",
          "age"
        ],
        [
          "Tom",
          12
        ],
        [
          "Jack",
          13
        ]
      ]
    };

The desired output should be:

 var result =  {
      "student": [
        {
          "name": "Tom",
          "age": 12
        },
        {
          "name": "Jack",
          "age": 13
        }
      ]
    }

An attempt was made using the following code:

var response = [];  
var keysCount = req.result[0].length; 
var responseCount = req.result.length - 1; 
var i = 0,
    j = 0,
    key;

for (j = 0; j < responseCount; j++) {
    for (i = 0; i < keysCount; i++) {
        key = req.result[0][i];
        response[j][key] = req.result[j + 1][i];
    }
} 
return response;

Unfortunately, the outcome did not meet the expected results.

Answer №1

One way to handle this situation is by iterating through the initial array and generating an array of objects for all subsequent arrays. Matching indexes are used to assign properties to the object:

var data = {
  "student": [
    [
      "name",
      "age"
    ],
    [
      "Tom",
      12
    ],
    [
      "Jack",
      13
    ]
  ]
};
// Extract the header array
var headers = data.student[0];
// Generate a new array by mapping over the other entries...
var newArray = data.student.slice(1).map(function(entry) {
  // Create a new object
  var newObj = {};
  
  // Populate it with values from matching indexes
  headers.forEach(function(key, index) {
    newObj[key] = entry[index];
  });
  
  // Return the new object
  return newObj;
});
console.log(newArray);

Answer №2

One approach is to create a function called tabularize that can organize an array of data with headers and rows.

This code snippet utilizes ES6. For ES5 compatibility, consider using a transpiler like Babel.

// original data structure   
var request = {
  "student": [
    [
      "name",
      "age"
    ],
    [
      "Tom",
      12
    ],
    [
      "Jack",
      13
    ]
  ]
};

// define tabularize function
var tabularize = ([headers, ...rows])=>
  rows.map(row=>
    headers.reduce((acc,h,i)=>
      Object.assign(acc, {[h]: row[i]}), {}));

// transform the object 
var request2 = {student: tabularize(request.student)};

// output the result
console.log(request2);

//=> {"student":[{"name":"Tom","age":12},{"name":"Jack","age":13}]}

You can also structure the request object directly by utilizing the tabularize function during object creation

// tabularize function
var tabularize = ([headers, ...rows])=>
  rows.map(row=>
    headers.reduce((acc,h,i)=>
      Object.assign(acc, {[h]: row[i]}), {}));

// specify the request object
var request = {
  student: tabularize([
    [
      "name",
      "age"
    ],
    [
      "Tom",
      12
    ],
    [
      "Jack",
      13
    ]
  ])
};

// display the outcome
console.log(request);

//=> {"student":[{"name":"Tom","age":12},{"name":"Jack","age":13}]}

Answer №3

To begin, let's create a simple function that constructs an object from two arrays - one containing keys and the other their corresponding values:

function makeObjectFromPairs(keys, values) {
  var object = {};

  for (var i = 0; i < keys.length; i++) {
    object[keys[i]] = values[i];
  }

  return object;
}

// makeObjectFromPairs(['a', 'b'], [1, 2]) === {a: 1, b: 2}

Next, we can utilize the first element of the students array as the keys, and each subsequent element as the values.

var keys = students[0];
var result = [];

for (var i = 1; i < students.length; i++) {
  result.push(makeObjectFromPairs(keys, students[i]);
}

While you may opt to use Array#map or similar methods instead of loops, this straightforward approach is often easier to grasp.

Correcting your initial code snippet

Given your earnest attempt at solving the task independently, let's take a closer look at your code to pinpoint the error. The crucial fix involves initializing each element in your output as an empty object before populating it with key/value pairs.

for (j = 0; j < responseCount; j++) {

    // Remember to set the response element to an empty object here.
    response[j] = {};

Answer №4

This is an alternative solution:

var data = {
    "people": [
        [
            "name",
            "age"
        ],
        [
            "Sally",
            22
        ],
        [
            "Mike",
            30
        ]
    ]
};

var result = {};
var peopleList = [];
var count = data.people.length - 1;
var i = 0,
    key;

for (i = 0; i < count; i++) {
    var person = {};
    data.people[0].forEach(function(attribute, index) {
        person[attribute] = data.people[1 + i][index];
    });
    peopleList.push(person)
}

result["people"] = peopleList;

console.log(result); // {"people":[{"name":"Sally","age":22},{"name":"Mike","age":30}]}

Answer №5

Using Lodash for a solution

var keys = _.head(request.student);
var valueGroups = _.flatten(_.zip(_.tail(request.student)));

var studentObjects = valueGroups.map(function(values){
    return values.reduce(function(obj, value, index){
        obj[keys[index]] = value;
    return obj;
  }, {});
});

console.log(studentObjects);

Check out the code on JsFiddle: https://jsfiddle.net/

Answer №6

Here is a straightforward solution using Javascript:

 var data =  {
      "students": [
        [
          "name",
          "age"
        ],
        [
          "Tom",
          12
        ],
        [
          "Jack",
          13
        ]
      ]
    };

var allStudents = [];
for(var i = 1; i < data.students.length; i++)
{
  var studentObj = { 'name' : data.students[i][0],
               'age' : data.students[i][1]
             }
    allStudents.push(studentObj);
}
data = { 'allStudents' : allStudents}

console.log(data);

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

Dynamically adding items in a row to a form panel using extjs

While using ExtJS 3.4, I faced a challenge with laying out three buttons in a row within a formpanel. After some research, I discovered that nesting item blocks might be the correct approach. Below is the code snippet showcasing what I have implemented: v ...

I keep encountering an error stating that parameter 1 for 'FormData' is not of type 'HTMLFormElement'. I am struggling to resolve this issue on my own. Can someone please assist me with fixing this problem?

Here is the snippet of code that I am struggling with: const authForm = useRef(); const handleSubmit = (e) => { e.preventDefault(); //formData let form = new FormData(authForm.current); console.log(form) } This code snippet shows how I added a ...

Developing in PHP and Laravel: Retrieving the Nth element from an array within an array, in increments of N

I have a new task where I need to implement a discount on every 10th order for a customer, starting from the beginning of their subscription. The data I need is coming from an external API call outside of Laravel. For example: [ [ order_id: xxxxx, ...

Executing the split function on a 2D array in Google Apps Script while maintaining the original column indexing

When running the split function on an array column in Google Apps Script, it generates multiple columns with varying numbers. Some rows may have 6 columns and others only 4. I want to adjust the output array to ensure all rows have an even number of colum ...

Using Rails version 4 along with bootstrap 3 modal, you can easily hide contents by simply doing nothing inside

Within my action.js.erb file, I have the following code: <%= render 'smthng' %> Inside the _smthng.js.erb file: ... $("#modal").modal("hide") ... When I trigger the action, the modal window does not hide. However, if I include $("#m ...

Ways to provide validation with JavaScript

I've created a table to input values for calculating specific averages. The form has a submit button that stores these values in a database. To prevent storing 0 values when submitting an empty form, I need to validate each textbox with JavaScript. H ...

Attempting to transfer information between components via a shared service

Currently, I am utilizing a service to transfer data between components. The code snippet for my component is as follows: constructor(private psService: ProjectShipmentService, private pdComp: ProjectDetailsComponent) { } ngOnInit() { this.psSe ...

Only one of the two scripts is functioning as intended

I'm facing an issue with two different scripts - the first one doesn't seem to work while the second one does. Oddly enough, when I remove the second script, the first one starts working. Can you help me find a solution? <script> // Ta ...

Redux - Refreshing the subtree state

How can I properly reset the subtree of a redux store without resetting the entire store? I want to target only the reducer subtree in question. Check out this example code: //initial state const initialState = { isFetching: false, error: '& ...

Exploring the realms of object-oriented programming with JavaScript, jQuery, and AJAX

Here is the code snippet I am working with: var Foo = function(){ this._temp="uh"; }; Foo.prototype._handler=function(data, textStatus){ alert(this._temp); } Foo.prototype.run=function(){ $.ajax({ url: '....', succ ...

Encode the array in JSON format and return it as a string without any

Currently, I am in the process of developing a basic GUI for my Linux executable using HTML/JavaScript and PHP. However, I have encountered an issue when attempting to call my executable with the system function while passing a JSON string as a parameter. ...

Retrieving information from a JSON source to populate a data table

Hello fellow developers... I'm currently facing an issue while trying to dynamically populate a data table with information fetched through a fetch request and stored in a Vuex instance variable. Here is the relevant code snippet: <script> impo ...

Encountering a "Uncaught TypeError: Cannot read property 'render' of undefined" error in Three.js when using an object literal

I've been working on converting my code to object literal style. While I was able to successfully create the scene, I'm encountering some issues with the animation. One specific error message that I'm getting is "Uncaught TypeError: Cannot ...

Using Firestore startAt() with Redux: a comparison of serializable and non-serializable scenarios

I find myself at a pivotal moment in my Firebase project and am seeking some general guidance. Here are the key points as I have gathered them through my research: When it comes to Firestore queries, there is a useful feature for pagination called startAt ...

Clicking the save button in the modal updates the text on both the current tab and any previously clicked tabs

I'm looking to implement tabs that, when clicking on the edit icon, open a modal for editing the content of each tab. The issue I'm currently encountering is that if I open the editor for one tab, close it without saving, then open the editor fo ...

Tips for fetching element values with webdriverio and mocha

browser.getValue('#username').then(function (value) { console.log('The value of the element is: '+value); }); If you are utilizing the browser object in webdriverio with mocha runner, simply provide the element ID to re ...

Three.js: Objects in the distance appear more subtle

Currently, I am developing a three.js scenario that showcases textured point sprites. These sprites obtain their textures from a single uniform, which is a 2D canvas containing the alphabet: https://i.stack.imgur.com/Ceh9x.png In my scene, all the letter ...

The Safari browser showcases the dropdown area in a unique way

Is there a way to make the dropdown area size consistent across different browsers like Chrome, Firefox, and Internet Explorer? Here is the code snippet: <div id="category-dropdown" style="float:left; display:inline-block; padding:8px 0px 0px 5px; dis ...

Tips for creating seamless image transitions using a toggle button

My transition effect is working smoothly, but I am having trouble setting it up for the image. How can I resolve this issue? I attempted the following: var lightsOff = document.querySelector("#lights-off"); var lightsOn = document.querySelector("#lights-o ...

Experiencing a java.lang.OutOfMemoryError while attempting to convert a large PDF file into a byte array

My attempt to read a large pdf file using byte Array isn't going as planned. Here is the code I am using: String RESULT "D/new/certficateVisualFinal.pdf"; try { FileInputStream fileInputStream=null; File file = new File(RESULT); ...