[SalesForce] create a map with keys = fields names and values = query result

I am trying to create a map from a result of a SOQL query,
this map contains the name of the fields as keys and the values of the query as values
for example:

List accounts = [SELECT Name, Email FROM Account];

and the map Map has this structure:

key         value
name        123 
email       test@test.co.uk

any ideas please ?

Best Answer

An SObject record has a very map-like structure by default.

Account record = [SELECT Name, Email FROM Account LIMIT 1];
system.debug(record.get('Name');
system.debug(record.get('Email');

It even supports put:

record.put('Email', 'newemailaddress@example.com');

However, if you absolutely must have a map for some reason, you can use serialization (a CPU intensive process) as follows:

String representation = JSON.serialize(record);
Map<String, Object> dataMap = (Map<String, Object>)JSON.deserializeUntyped(representation);
dataMap.remove('attributes');
Related Topic