Wrap object properties of type string with arrays - JavaScript

When working with objects, you may need to ensure all properties are arrays. This is useful for normalizing data structures where some properties might be strings while others are already arrays.

The Problem

Consider an object where some properties are strings and others are arrays. To process them uniformly, you need all properties to be arrays:

var details = { 
    name: ["John", "David"], 
    age1: "21", 
    age2: "23" 
};

console.log("Original object:");
console.log(details);
Original object:
{ name: [ 'John', 'David' ], age1: '21', age2: '23' }

Solution Using Object.keys() and reduce()

Use Object.keys() with reduce() and concat() to wrap all properties in arrays:

var details = { 
    name: ["John", "David"], 
    age1: "21", 
    age2: "23" 
};

var output = Object
    .keys(details)
    .reduce((obj, tempKey) =>
        (obj[tempKey] = [].concat(details[tempKey]), obj), {});

console.log("Wrapped object:");
console.log(output);
Wrapped object:
{ name: [ 'John', 'David' ], age1: [ '21' ], age2: [ '23' ] }

How It Works

The solution works in these steps:

  • Object.keys(details) returns an array of property names
  • reduce() iterates through each key to build a new object
  • [].concat(details[tempKey]) wraps each value in an array
  • If the value is already an array, concat() preserves it
  • If the value is a string, concat() creates a new array containing that string

Alternative Approach

You can also use a more explicit approach with Array.isArray():

var details = { 
    name: ["John", "David"], 
    age1: "21", 
    age2: "23" 
};

var output = {};
Object.keys(details).forEach(key => {
    output[key] = Array.isArray(details[key]) ? details[key] : [details[key]];
});

console.log("Alternative approach result:");
console.log(output);
Alternative approach result:
{ name: [ 'John', 'David' ], age1: [ '21' ], age2: [ '23' ] }

Conclusion

Use Object.keys() with reduce() and concat() to efficiently wrap all object properties in arrays. This technique is particularly useful for data normalization and ensuring consistent array-based processing.

Updated on: 2026-03-15T23:19:00+05:30

593 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements