Navigate through an array using just one index, each element of which holds multiple objects

Here is a dataset that needs reformatting

let data = [
  {
    apple:1,
    banana:2,
    cherry:3
  },
  {
    apple:4,
    banana:5,
    cherry:6
  },
  {
    apple:7,
    banana:8,
    cherry:9
  }
]

The desired format for the data is as follows:

{
   apple: [1,4,7],
   banana: [2,5,8],
   cherry: [3,6,9]
}

Below is a proposed solution:

let data = [
  {
    apple:1,
    banana:2,
    cherry:3
  },
  {
    apple:4,
    banana:5,
    cherry:6
  },
  {
    apple:7,
    banana:8,
    cherry:9
  }
]

function reformatData (data) {
  console.log(typeof data) // WHY IS THIS RETURNING AN OBJECT???
  let keys = Object.keys(data[0])
  const resultObj = {}
  for (let key of keys) {
    resultObj[key] = []
  }
  data.forEach((x,idx)=> {
    for (let key in x) {
      resultObj[key].push(x[key])
    }
  })
  return resultObj
}

reformatData(data)

Although this code works, it may not be the most efficient. I am struggling with understanding the following concepts:

  • Initially, data appears to me as an array with one index containing three objects. For instance, data[0] = {obj1},{obj2},{obj3}, but when I check its type using typeof, it shows as an object.
  • When I log data at a specific index like data[1], it displays {apple:4,banana:5,cherry:6} resembling an array.
  • I am confused about what kind of data structure this is and what is happening here?

Please provide a more efficient solution and clarify these concepts for me.

Answer №1

Experiment

function testFunction (data) {
  let finalObject = {};

  data.forEach((item) => {
    for (let property in item) {
      if (finalObject.hasOwnProperty(property)) {
        finalObject[property].push(item[property]);
      } else {
        finalObject[property] = [item[property]];
      }
    }
  });

  return finalObject;
}

Answer №2

If you want to verify if a variable is an array, you can utilize the Array.isArray() method. The typeof operator will return 'object' for arrays since they are objects in JavaScript that are created using the Object constructor.

To achieve the desired result, you just need to iterate over the array and store the values in an object.

let arr = [
  {
    a:1,
    b:2,
    c:3
  },
  {
    a:4,
    b:5,
    c:6
  },
  {
    a:7,
    b:8,
    c:9
  }
]

var res = {};
arr.forEach((obj) => {
   Object.entries(obj).forEach(([key, val]) => {
      if(res[key]) {
         res[key].push(val);
      } else {
         res[key] = [val];
      }
   })
});

console.log(res);

Answer №3

If you want to achieve this functionality, you can utilize the array method reduce().

  • To start, iterate through all the keys of each object in the array by using Object.keys(o) within the reduce() method.
  • Inside the iteration, initialize the accumulator with the same key as currently being iterated and set the initial value of that key to an empty array [].
  • By utilizing r[k].push(o[k]), you will add the corresponding key values into this array.
  • Finally, return the resulting object r from the .reduce() method.

let arr = [{a:1,b:2,c:3},{a:4,b:5,c:6},{a:7,b:8,c:9}];
const res = arr.reduce((r, o) => {
  Object.keys(o).forEach((k) => {
    r[k] = r[k] || [];
    r[k].push(o[k])
  });
  return r;
}, {})

console.log(res)
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №4

Here is a solution you can experiment with:

let data = [
  {
    a:1,
    b:2,
    c:3
  },
  {
    a:4,
    b:5,
    c:6
  },
  {
    a:7,
    b:8,
    c:9
  }
];

let result = {};

Object.values(data).forEach(obj => {
  Object.keys(obj).forEach(prop => {
   if (typeof result[prop] === 'undefined') {
     result[prop] = [];
   }
   result[prop].push(obj[prop])
  })
})

console.log(result);

Answer №5

Combine values of the same keys in an object using multiple forEach loops.

let data = [
  {
    x: 1,
    y: 2,
    z: 3
  },
  {
    x: 4,
    y: 5,
    z: 6
  },
  {
    x: 7,
    y: 8,
    z: 9
  }
];

const resultObj = {};
data.forEach(item => {
  Object.keys(item).forEach(
    key => (resultObj[key] = key in resultObj ? [...resultObj[key], item[key]] : [item[key]])
  );
});

console.log(resultObj);

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

Refreshing/Redrawing/Resizing a panel in jQuery Layout when toggling the visibility of a header or footer

Currently utilizing a standard jQuery layout with north, south, west, east, and center sections as outlined in the documentation. In both the west and center panels, there are header and footer panes included. While everything is functioning correctly, I ...

Using the underscore template to dynamically assign images

Currently, I am utilizing underscore templates to showcase a HTML list demonstrating a series of contact details. The format of the template is as follows: <li> <span class="name">Name: <=%data.name%></span> <span class="emai ...

Generate several different elements

Is it possible to use Vue.js to render a component multiple times based on a variable? For instance, I have a size variable set to 5 and I want to display the Widget component 5 times. Here is my current code snippet: Template : <template> &l ...

What could be causing my toString method to return null when used in an array of elements in Java?

I have an array with the elements "a b c d e". I then apply a reverse method to switch the positions of the elements in the array to "e d c b a" I am attempting to display the items in the array using this toString method: public String toString() { ...

Enhancing the Efficiency of Android Programming

For my application, I am currently displaying 12 markers on a map, each of which triggers a dialog box showing the location's address when tapped. However, I believe there is a more efficient way to handle this. I have been experimenting with creating ...

Repeating audio playback in HTML5 with a pause option

I need to set up a loop with a 10-minute delay. Once the loop starts and finishes, there should be another 10-minute delay before it automatically restarts again. $audio_code = '<div style="display: none;">' . '<audio id="war_sound ...

Utilizing the power of JQuery's each() function alongside UI.sortable() for enhanced

Need help with updating data-priority attribute after sorting an unordered list using jQuery ui. Currently, the attribute is only set on load and not updated after each sort. I have created a fiddle to demonstrate the issue. It seems like a simple fix but ...

Implementing jQuery and JavaScript validation for email addresses and usernames

Are the online validations being used incorrectly or is there a serious issue with them? I came across an example of a site using jQuery validation, but when I entered "44" for a name and ##@yahoo.com for an email address, no warning appeared. I haven&apo ...

Error: the keyword "module" has not been properly defined

Struggling to run this web app, initially encountered: (node:12960) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension. C:\Users\J\react-messenger\stream-chat-boilerp ...

Retrieve just a single item of an array

My mongodb collection is structured in the following way: /* 1 */ { "_id" : ObjectId("551fc02d26a8a48c32000029"), "nome" : "ist1", "username" : "istituzione1", "email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail ...

Separate the selected option in the TEXTAREA by commas to make it easier to

Can you assist me with integrating this example? I have the following elements: When adding a textarea, I require an option to be selected and separated by a comma. For instance: Here I will select an option: Subsequently, this chosen option must be ad ...

Script unable to retrieve PHP data with AJAX success function

I need help retrieving database rows using PHP. The JavaScript success function doesn't seem to be working. Can anyone spot a potential issue in the PHP code? Here is the PHP code: $id=$_GET['id']; $stmt = $db->prepare("SELECT * FROM b ...

Allowing input fields to accept decimal numbers

I am currently facing an issue with an input field that is set to type=number, which does not allow for decimal numbers. However, I need to enable users to input decimal numbers but haven't been able to make it work. Would using regex be a possible so ...

Xap or js Silverlight media player

Currently developing a Silverlight video player, I stumbled upon the JW Player for inspiration. I know that Silverlight apps are typically contained within .xap files, but JW Player utilizes JavaScript scripts to implement Silverlight logic. Can you plea ...

Fade effect on vectorial HTML map with Javascript (mouseover)

I am trying to add a fade in and fade out effect to my image switching function, but I have not been able to adapt other fade methods into mine successfully. Do you have any suggestions on how I can achieve this? Here is an example of what I currently ha ...

Display larger images dynamically by hovering over thumbnails using PHP

Is there a way to display an image when I hover over a thumbnail using PHP, similar to the functionality on this website? I'm looking for a solution to implement this feature. ...

Loading game resources in advance for future or immediate utilization

I'm currently developing a game UI that involves a large number of image files, totaling around 30MB in size. I've been caching these images to the disk using service workers, but some of them are quite large at 3MB each. Even when they are retri ...

Retrieve data from a JSON file URL using a GET request and save the response to be accessed globally when the Vue.js application is initialized

Consider this scenario - I have a Vue.js component where I need to display the name of a user based on their ID. The only information I have is the user's ID. However, I also have a JSON file URL that contains all the user objects with their names and ...

What is the best way to set up a JSON attribute with properly formatted JSON data?

Within this code snippet, the variable some is assigned a JSON string that requires expansion and proper indentation for improved readability. export class MyComponent implements OnInit { some:any = JSON.parse('[{"id":"EN","fill":"blue","classb ...

Form submission is not functioning as expected

I am having trouble with my form submission. When I try to submit the form, nothing happens. I have tried various solutions but have not been able to resolve the issue. I have reviewed all available resources but still cannot figure out why my code is not ...