• 0

[JavaScript] Loop through Object, grouping every 4 items


Question

I have an object that looks like the following...

rawData = ['Pizza', 'Pepperoni', 'Veggie', 'Hawaiian', 'Coffee', 'Cappuccino', 'Mocha', 'Latte', 'CEOs', 'Tim Cook', 'Mark Zuckerberg', 'Satya Nadella', 'Thanksgiving Food', 'Turkey', 'Cranberry Sauce', 'Pumpkin Pie']

 

I'd like to convert into the following format using JS, but an not sure how to loop through it...

outputData = [
    {
        'category': 'Pizza',
        'example1': 'Pepperoni',
        'example2': 'Veggie',
        'example3': 'Hawaiian'
    },
    {
        'category': 'Coffee',
        'example1': 'Cappuccino',
        'example2': 'Mocha',
        'example3': 'Latte', 
    },
    {
        'category': 'CEOs',
        'example1': 'Tim Cook',
        'example2': 'Mark Zuckerberg',
        'example3': 'Satya Nadella'
    },
    {
        'category': 'Thanksgiving Food',
        'example1': 'Turkey',
        'example2': 'Cranberry Sauce',
        'example3': 'Pumpkin Pie'
    }
]


When you examine the "rawData" object, you'll notice it has 4 sets of data:

  • (Item 1) Category Name.
  • (Items 2, 3 and 4) 3 Examples from that Category.

Then the object repeats. 
 

In my example, I've included 4 sample data sets but I can imagine there could be an n number of them.

I'm awful at loops and this one of driving me nuts!  I hope someone can help me.

8 answers to this question

Recommended Posts

  • 0

Here's a very simple, easy to read solution. Just use a while loop that runs until the array is empty and splice off 4 items at a time off the array after assigning your values to an new object and pushing it to the output array. No complicated for loops or messy index offsets.

 

let outputData = [];

while (rawData.length > 0) {

  outputData.push({
    category: rawData[0],
    example1: rawData[1],
    example2: rawData[2],
    example3: rawData[3]
  });

  rawData.splice(0,4);

}

 

If you need the rawData array to remain untouched just clone the array like this and use that array instead.

let rawClone = [...rawData];

 

I have a hard time believing these questions are for personal projects lol

Edited by PmRd
  • 0
  On 23/11/2023 at 19:44, Brian Miller said:

Thanks! You made it so simple, I didn't think of doing that way.

And yes, this is a home project.  I'll publish my personal in a few weeks and you'll see. 😉 

Expand  

Glad to help

  • 0
  On 23/11/2023 at 19:47, Brian Miller said:

By the way, why did you use "LET" to define the variable, and not a "VAR"?

Is there a difference?

Expand  

Force of habit lol, I usually always work with classes. In this scenario var would work, but if you put that code inside a function that returns the array you're better off using let since it will limit those variables to the scope of the function. I only use var for global variables.

  • 0
  On 23/11/2023 at 19:50, PmRd said:

Force of habit lol, I usually always work with classes. In this scenario var would work, but if you put that code inside a function that returns the array you're better off using let since it will limit those variables to the scope of the function. I only use var for global variables.

Expand  

Thank you.

I'm learning more and more every day.

  • 0

You can do neat stuff like this with let, a scope a basically { anything inside brackets }, and yes you can just put plain brackets anywhere you want. 

{ // scope 1
  
  let test = "test 1";
  let boop = "boop";
  var meep = "meep";
  
  { // scope 2
    
    console.log(boop); //this would return "boop" because this scope is nested therefore it can access variables from its parent scope.
    console.log(test); //however, this would raise an error because a variable with the same name is declared lower in this scope
    let test = "test 2"; // this test variable will only exist in scope 2 and doesn't affect test in scope 1
    console.log(test); //this would return "test 2"
    
  } // scope 2 end
  
  console.log(test); //this would return "test 1" because we are back in scope 1

} // scope 1 end


console.log(meep); //this would return "meep" because var is always global even when delcared inside a scope
console.log(test); //this would raise an error because we are outside scope 1 

It's best practice and saves a lot of headaches to use let inside loops and for temporary variables inside a function. Hope this helps!

Edited by PmRd

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Get this 27-inch ASUS VA279QG 120Hz monitor for dirt-cheap by Taras Buria If you are on a very tight budget but you still want to upgrade your monitor to something more exciting than a standard 60Hz office monitor, ASUS has a perfect deal for you. The VA279QG is currently available for as little as $109, and for this money, you get quite a lot of a monitor. The ASUS VA279QG is a big 27-inch IPS monitor with a classic FullHD resolution and a wide 178-degree viewing angle. It can operate with a refresh rate of 120Hz, which is more than enough for buttery-smooth gaming. And since the monitor is FullHD, you will be able to see high refresh rates in more games since your GPU will have to render fewer pixels at 120Hz. Besides, the monitor supports variable refresh rate (VRR), a feature that can further reduce stutters by dynamically adjusting the refresh rate to your FPS. Other display specs include a 1ms MPRT response time, 16.7 million colors, 99% sRGB coverage, and a typical brightness of 300 nits. It is also covered with an anti-glare coating to reduce reflections. Ports-wise, you get one DisplayPort 1.2, one HDMI 1.4, one VGA, and one headphone jack. There are also two 2W speakers, but set your expectation right—these are unlikely to blow your mind with high-quality audio. Finally, there is a VESA 100 mount and a cutout in the base, which lets you mount your phone, namecard, or other small items for extra convenience. 27-inch ASUS VA279QG 120Hz IPS Gaming Monitor - $109 | 22% off on Amazon US This Amazon deal is US-specific and not available in other regions unless specified. If you don't like it or want to look at more options, check out the Amazon US deals page here. Get Prime (SNAP), Prime Video, Audible Plus or Kindle / Music Unlimited. Free for 30 days. As an Amazon Associate, we earn from qualifying purchases.
    • lol See... one is only 100% when it's by itself. I live for exceptions to the rule... our talk point was in reference in comparing Vista (not SP1/2) release vs. 7. Any OS will run stable once enough work has been put into it... hell, even Windows 95 had six versions before she was finally complete(d)... just about, what, six or seven months before 98 became available?
    • 3uTools 3.26.007 by Razvan Serea 3uTools is a powerful iOS management tool that allows users to efficiently handle their iPhone or iPad without relying on iTunes. It offers seamless data transfer, one-click backup and restore, firmware updates, and a built-in file explorer for easy access to system files. Users can also manage apps, contacts, and media, including photos, videos, and ringtones, all within a simple and intuitive interface. For optimization and maintenance, 3uTools provides battery health monitoring, real-time device information, and system cleanup tools. It also includes features like screen recording, video conversion, and iCloud backup management, making it an essential tool for iOS users looking for greater control over their devices. Key features of 3uTools: iOS device management App installation and removal Firmware downloads and updates Backup and restore functions Data transfer between iOS and PC Ringtone creation Custom wallpaper management Device flashing File system explorer Battery health monitoring Screen capture and recording Video and photo management iCloud backup support Flashing and restoring iOS without data loss 3uTools 3.26.007 changelog: Easy Flash supports iOS 26.0 flashing. Optimized Virtual Location. Fixed some known bugs. Download: 3uTools 3.26.007 | 186.0 MB (Freeware) Download: 3uTools 32-bit | 192.0 MB View: 3uTools Home Page | macOS | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • The development time of this Operating System will have competition with the development time of Star Citizen 😂
    • I saw the 300 in the image and thought it was the number of cores! 🤣
  • Recent Achievements

    • Explorer
      treker_ed went up a rank
      Explorer
    • Apprentice
      CHUNWEI went up a rank
      Apprentice
    • Veteran
      1337ish went up a rank
      Veteran
    • Rookie
      john.al went up a rank
      Rookie
    • Week One Done
      patrickft456 earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      654
    2. 2
      ATLien_0
      271
    3. 3
      +FloatingFatMan
      176
    4. 4
      Michael Scrip
      157
    5. 5
      Steven P.
      136
  • Tell a friend

    Love Neowin? Tell a friend!