Rihana
Rihana

Reputation: 443

Extract data from array of objects (Slightly complicated issue)

I have an array of objects as follows.

Array[0-2]
   0: Object
           Name: 'Rick'
           City: 'Sunnyvale'
           FactorJSONMap: "{"Id":"234","Country":"USA"}"
   1: Object
           Name: 'Diana'
           City: 'Santa Clara'
           FactorJSONMap: "{"Id":"124","Country":"USA"}"
   2: Object
           Name: 'Thiago'
           City: 'New Jeresy'
           FactorJSONMap: "{"Id":"673","Country":"USA"}"

I am able to loop through the elements 'Name' and 'City' properly. However there is an element 'FactorJSONMap'. this is coming from database. I am not able to loop through this generally.

Can anyone please let me know if there is a way to convert above format of data into the below format.

Please note. The FactorJSONMap is dynamic and there can be different elements. here it has 'Id' and 'City' currently. It can have 'Id', 'City' and 'Sex'.

Is there a way i can pull above data and convert into this simple array of objects form.

Array[0-2]
   0: Object
           Name: 'Rick'
           City: 'Sunnyvale'
           Id: '234'
           Country:'USA'
   1: Object
           Name: 'Diana'
           City: 'Santa Clara'
           Id: '124'
           Country:'USA'
   2: Object
           Name: 'Thiago'
           City: 'New Jeresy'
           Id: '673'
           Country:'USA'

Upvotes: 0

Views: 65

Answers (1)

zfrisch
zfrisch

Reputation: 8670

You can simply use the parse method of the JSON object to get the data within the FactorJSONMap into object format, then assign it to the parent object within the array. Once you've iterated through all Objects in the array, the returned Object Array will have all the nested properties listed within the first level.

https://jsfiddle.net/4h72h6b8/3/

function traverseData(data) {
  for(let data_obj of data) {
  Object.assign(data_obj, JSON.parse(data_obj.FactorJSONMap));
  delete data_obj.FactorJSONMap;
  }
  return data;
};

In the example you will see the result in the console log.

Upvotes: 1

Related Questions