Arrays and objects are two commonly used data structures. In practical development, you often need to convert an array into an object for easier manipulation. This article will explain how to convert an array to an object and how to flexibly manipulate object properties after the conversion.
In PHP, one common way to convert an array to an object is by using the Object.assign() method. This method takes two parameters: the target object and the source object to copy from. After conversion, the array elements will become properties of the object.
const arr = [
'foo'
,
'bar'
,
'baz'
];
const obj = Object.assign({}, arr);
console.log(obj);
// Output: {0: "foo", 1: "bar", 2: "baz"}
With the above code, elements in the array will be copied to a new empty object, and the indices 0 through 2 will become properties of that object.
After converting the array to an object, you can access and modify the object's properties using dot notation or bracket notation.
console.log(obj.0);
// Output: foo
console.log(obj[
'1'
]);
// Output: bar
You can also modify the object's properties using assignment.
obj.2 =
'qux'
;
console.log(obj);
// Output: {0: "foo", 1: "bar", 2: "qux"}
In real-world development, converting an array to an object can be applied in many scenarios. For example:
By using the Object.assign() method, you can easily convert an array into an object. After conversion, the object supports both dot notation and bracket notation to access and modify its properties. This method provides great flexibility in various development scenarios, making it an indispensable tool.