Convert an array of JSON objects to an associative array

Assuming I have 2 arrays of JSON objects that look like this:

Resources

[{ "DefinitionId": 193041, "ResourceId": -2147290607, "AssetId": 193041 }, { "DefinitionId": 193042, "ResourceId": -2147290603, "AssetId": 193042 }] 

Resourceource

 [193041, 193041, 193041, 193042] 

Usage example:

I need to list the details from my JSONObject resource for each ResourceId. For example, I want to output an AssetId for each ResourceId in ResourceIds .

My plan:

I thought it would be an elegant solution to convert my Resources JSON into an associative array so that I could access the AssetId for my ResourceId '193041' as follows: Resources[193041].AssetId . Problem: I could only think of long code to convert my above Resources JSON into an associative JSON object.

Question:

How can I convert the above array of JSON Resources objects to an array of associative objects with ResourceId key?

Desired .json resources:

 { "-2147290607": { "DefinitionId": 193041, "ResourceId": -2147290607, "AssetId": 193041 }, "-2147290603": { "DefinitionId": 193042, "ResourceId": -2147290603, "AssetId": 193042 } } 
+7
json javascript
source share
3 answers

You can use an object and iterate over an array using Array#forEach

The forEach() method executes the provided function once for an array element.

and set the element with a property named a.ResourceId .

The callback uses the Arrow function because there is only one purpose.

 var data = [{ "DefinitionId": 193041, "ResourceId": -2147290607, "AssetId": 193041 }, { "DefinitionId": 193042, "ResourceId": -2147290603, "AssetId": 193042 }], object = {}; data.forEach(a => object[a.ResourceId] = a); console.log(object); 
+2
source share

You can use reduce :

 var resources = [{ "DefinitionId": 193041, "ResourceId": -2147290607, "AssetId": 193041 }, { "DefinitionId": 193042, "ResourceId": -2147290603, "AssetId": 193042 }]; var resourceIds =[193041, 193041, 193041, 193042]; var res = resources.reduce( function(prev, curr) { // Check AssetId // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf if ( resourceIds.indexOf( curr.AssetId ) >= 0 ) prev[ curr.ResourceId ] = curr; return prev; }, {} ); var resJSON = JSON.stringify( res ); 
+1
source share
 var Resources = [{ "DefinitionId": 193041, "ResourceId": -2147290607, "AssetId": 193041 }, { "DefinitionId": 193042, "ResourceId": -2147290603, "AssetId": 193042 }]; Resources.find(function(value){return value.ResourceId === -2147290603}).AssetId 

or use lodash / underscore for an elegant solution: _.find (Resources, {ResourceId: -2147290603}). AssetId;

With this, we can find the required AssetId by simply passing the ResourceId. We can even skip JSON conversion for simplicity.

0
source share

All Articles