Current Location: Home> Latest Articles> How to Convert Arrays to Objects and Manipulate Object Properties

How to Convert Arrays to Objects and Manipulate Object Properties

M66 2025-07-29

Convert Array to Object: How to Manipulate Object Properties

In PHP or JavaScript development, arrays and objects are two of the most commonly used data structures. In some cases, you may need to convert an array into an object for easier property manipulation. This article will introduce how to convert arrays to objects and provide common methods for manipulating their properties.

Converting Arrays to Objects

To convert an array into an object, you can use the Object.assign() method in JavaScript. This method takes two arguments: the target object and the source object. When you pass an array to Object.assign(), it will use the array's indices as property names and the array's values as property values to create a new object.

const arr = ['foo', 'bar', 'baz'];
const obj = Object.assign({}, arr);
console.log(obj); // Output: {0: 'foo', 1: 'bar', 2: 'baz'}

The above code converts each element in the array into an object property, with the array's indices becoming the property names of the new object obj.

Manipulating Object Properties

After converting the array to an object, you can use dot notation or bracket notation to access the object's properties. For example:

console.log(obj[0]); // Output: foo
console.log(obj['1']); // Output: bar

You can also modify the object properties using the assignment operator:

obj[2] = 'qux';
console.log(obj); // Output: {0: 'foo', 1: 'bar', 2: 'qux'}

This allows you to easily update the content of the object.

Real-World Use Cases

Converting arrays to objects can be useful in various scenarios. Here are a few common use cases:

  • Convert array data returned from the server into an object for easier manipulation on the client side.
  • Store form data as an object for better management and submission.
  • Convert dynamic data lists into objects to generate dynamic UI elements.

Conclusion

By using the Object.assign() method to convert arrays to objects, you can easily access and manipulate object properties through dot or bracket notation. This conversion is highly useful in real-world development, allowing you to efficiently manage and process data.