• 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

    • Glad they aren't hiking the price $10. If anything they should offer a $10 discount to anyone that provides a receipt for that awful movie.
    • At this point, with this - they have proven it to be a gimmick to “look like Windows”, rather than “here’s a nice useable OS”
    • AMD releases new Windows 10 and 11 chipset driver for Ryzen processors by Taras Buria Following a major firmware update for a TPM-Pluton security flaw, AMD has a new chipset driver for all of its supported Ryzen platforms and processors. Version 7.06.02.123 is now available for download, and it adds unnamed bug fixes and an important addition to the AMD PPM Provisioning File driver, which improves the security of the component. The security update in question is CETCOMPAT support for the AMD PPM Provisioning File driver. CET or Control-flow Enforcement Technology (CET) was introduced for Windows 10 versions 20H1 and 20H2 in early 2021. In a nutshell, it is an Intel-developed protection system that prevents malware from changing memory addresses (Shadow Stack) or redirecting programs to malicious code by ensuring they use only approved, safe locations (Indirect Branch Tracking). AMD brought CETCOMPACT support to parts of its Ryzen chipset driver suite (the driver you download and install is a set of different drivers serving different purposes that AMD lets you select on the first screen) in October 2024. Now, with driver 7.06.02.123, CET compatibility has been added to the AMD PPM Provisioning File driver, which is responsible for core parking and power management. Here is the list of updated drivers in today's release: Driver Version (Windows 10) Version (Windows 11) Changelog AMD PPM Provisioning File Driver 8.0.0.53 8.0.0.53 CETCOMPAT support is added AMD PMF-6000 Series Driver 24.0.6.0 24.0.6.0 Bug fixes AMD S0i3 Filter Driver 4.5.0.1020 4.5.0.1020 AMD 3D V-Cache Performance Optimizer Driver 1.0.0.11 1.0.0.11 AMD PMF-7040 Series Driver 24.2.6.0 24.2.6.0 AMD PMF-8000Series Driver 25.5.25.0 25.5.25.0 AMD PMF Ryzen AI 300 Series Driver 1 Not Applicable 25.6.28.0 AMD's latest Ryzen chipset driver supports 64-bit Windows 10 and 11 systems with the following motherboards: A-Series B-Series X-Series Threadripper AMD A320 AMD A520 AMD B350 AMD B450 AMD B550 AMD B650 / B650E AMD X370 AMD X470 AMD X570 AMD X670 / X670E AMD X870 / X870E AMD TRX40 AMD TRX50 AMD WRX80 AMD WRX90 You can download AMD Ryzen Chipset Driver 7.0.6.02.123 from the official support website. Full release notes and additional information is available on the same page.
    • I never got to experience BOB Hello even now because gaming laptops I bought always omitted the IR camera. And the standalone cameras for BOB Hello are super expensive
    • I wonder what $99 Chinese cellphone this phone will be based on. Whoever is dumb enough to buy the phone and/or get this service deserves everything they get.
  • 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
      644
    2. 2
      ATLien_0
      274
    3. 3
      +FloatingFatMan
      174
    4. 4
      Michael Scrip
      156
    5. 5
      Steven P.
      137
  • Tell a friend

    Love Neowin? Tell a friend!