Flat a JavaScript array of objects into an object

To flatten a JavaScript array of objects into a single object, we can create a function that iterates through each object in the array and combines their properties. This technique is useful when you need to merge multiple objects while preserving unique property names by appending indices.

Basic Approach

The most straightforward method is to loop through the array and create new property names by appending the array index to each original property name.

// Example array of objects
const notes = [{
    title: 'Hello world',
    id: 1
}, {
    title: 'Grab a coffee',
    id: 2
}, {
    title: 'Start coding',
    id: 3
}, {
    title: 'Have lunch',
    id: 4
}, {
    title: 'Have dinner',
    id: 5
}, {
    title: 'Go to bed',
    id: 6
}];

const returnFlattenObject = (arr) => {
    const flatObject = {};
    for(let i = 0; i < arr.length; i++) {
        for(const property in arr[i]) {
            flatObject[`${property}_${i}`] = arr[i][property];
        }
    }
    return flatObject;
}

console.log(returnFlattenObject(notes));
{
  title_0: 'Hello world',
  id_0: 1,
  title_1: 'Grab a coffee',
  id_1: 2,
  title_2: 'Start coding',
  id_2: 3,
  title_3: 'Have lunch',
  id_3: 4,
  title_4: 'Have dinner',
  id_4: 5,
  title_5: 'Go to bed',
  id_5: 6
}

Using Object.assign() and Spread Operator

An alternative approach uses modern JavaScript features for a more concise solution:

const flattenWithSpread = (arr) => {
    return Object.assign({}, ...arr.map((obj, index) => {
        return Object.fromEntries(
            Object.entries(obj).map(([key, value]) => [`${key}_${index}`, value])
        );
    }));
}

const notes2 = [
    { name: 'John', age: 30 },
    { name: 'Jane', age: 25 },
    { name: 'Bob', age: 35 }
];

console.log(flattenWithSpread(notes2));
{
  name_0: 'John',
  age_0: 30,
  name_1: 'Jane',
  age_1: 25,
  name_2: 'Bob',
  age_2: 35
}

Comparison

Method Readability Performance Browser Support
For loop approach High Fast All browsers
Object.assign() + map Medium Slower ES6+ required

Time and Space Complexity

Both approaches have:

  • Time Complexity: O(m×n) where n is the array length and m is the average number of properties per object
  • Space Complexity: O(m×n) for storing the flattened object properties

Conclusion

Flattening an array of objects into a single object is useful for data transformation. The for-loop approach offers better performance and browser compatibility, while modern methods provide more concise code.

Updated on: 2026-03-15T23:18:59+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements