In JavaScript, you may encounter situations where you need to consolidate an array of objects into a single encompassing object. For instance, you might have:
[ { key: '11', value: '1100', $$hashKey: '00X' }, { key: '22', value: '2200', $$hashKey: '018' } ];
and want to convert it into:
{ "11": "1100", "22": "2200" }
This transformation can be effortlessly accomplished using the reduce() method, as seen in the following snippet:
var arr = [{key:"11", value:"1100"},{key:"22", value:"2200"}]; var object = arr.reduce( (obj, item) => Object.assign(obj, { [item.key]: item.value }), {}); console.log(object)
The above is the detailed content of How to Convert a JavaScript Array of Objects into a Single Object?. For more information, please follow other related articles on the PHP Chinese website!