Array of Object to Object of Objects Manipulation using Javascript

Converting Array of Objects into Object of Objects in JavaScript

Converting an Array of Objects into an Object of Objects in JavaScript

Hey there, JavaScript enthusiasts! 🚀

Today, we’re diving into a fun and practical coding challenge: converting an array of objects into an object of objects. This is a neat trick that can come in handy when you need to transform your data structure for easier access and manipulation. Let’s jump right in!

The Challenge

Imagine we have an array of objects representing the best film Oscar winners:


const best_film_oscar = [
  { year: 2024, movie: "Oppenheimer" },
  { year: 2023, movie: "Everything Everywhere All at Once" },
  { year: 2022, name: "Coda" }
];
    

Our goal is to transform this array into an object of objects, where the keys are the years, and the values are the movies. The desired output looks like this:


const output = {
  2024: { movie: "Oppenheimer" },
  2023: { movie: "Everything Everywhere All at Once" },
  2022: { name: "Coda" }
};
    

The Solution

To achieve this, we’ll write a simple JavaScript function that iterates over the array and constructs the desired object. Here’s how you can do it:


const array_to_object = arr => {
  const temp_obj = {};
  for (let i = 0; i < arr.length; i++) {
    const key = arr[i]['year'];
    temp_obj[key] = arr[i];
    delete temp_obj[key]['year'];
  }
  return temp_obj;
};

const output = array_to_object(best_film_oscar);
console.log(output);
    

Let’s break down the code step-by-step:

  1. Initialize an Empty Object: We start by creating an empty object called temp_obj.
  2. Loop Through the Array: We use a for loop to iterate over each element in the array.
  3. Set the Key: For each element, we use the year property as the key for our new object.
  4. Assign the Object: We assign the entire object (without the year property) to this key.
  5. Delete the Year Property: Since we don’t need the year property in the inner objects, we delete it.
  6. Return the Result: Finally, we return the newly created object.

Why This Works

This method is efficient and easy to understand, making it perfect for JavaScript beginners. By iterating over the array and using the year property as keys, we can quickly transform our data into the desired structure.

Try It Yourself!

Copy the code and run it in your favorite JavaScript environment. You'll see how simple and powerful this transformation can be.

Happy coding! 🎉

Comments

Popular posts from this blog

What is .md File ?