user142617
user142617

Reputation: 386

Javascript object flatten to array

I have been trying today to flatten an object array. I cannot achieve what I need, I need to access to inner most element( 1st ) to the outer most element ( 4th ) here is a sample of the data there are some null values which might make it complex:

   {
      "School":"Arsenal 2011",          //4th Element in new array
      "Group":{
         "Name":"Previous",             //3rd Element in new array
         "ParentGroup":{
            "Name":"Arsenal",           //2nd Element in new array
            "ParentGroup":{
               "Name":"USA",            //1st Element in new array
               "ParentGroup":null
            }
         }
      },
      "GroupDisplayText":null,
      "Publisher":"Abbot",
      "PublishedDate":"2011",
      "PublishersWebsite":"http://google.com/USA/ADW%202011/Arsenal%202011.pdf"
   },
   {
      "School":"New York 2000",
      "Group":{
         "Name":"New York",
         "ParentGroup":{
            "Name":"USA",
            "ParentGroup":null
         }
      },
      "GroupDisplayText":null,
      "Publisher":"DoE",
      "PublishedDate":"2000",
      "PublishersWebsite":"http://google.com/USA/New York%202000%20Tables.pdf"
   }

The output array I would like is:

array[0] = { "USA","Arsenal","Previous" } array[x] = for all the other data

How would I do this in Javascript?

I have added a plunker if it helps

https://plnkr.co/edit/LNlHArCob4Bix8VYHFwI?p=preview

Thanks

Upvotes: 0

Views: 80

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386560

You could take an iterative check for the nested properties.

var data = [{ School: "Arsenal 2011", Group: { Name: "Previous", ParentGroup: { Name: "Arsenal", ParentGroup: { Name: "USA", ParentGroup: null } } }, GroupDisplayText: null, Publisher: "Abbot", PublishedDate: "2011", PublishersWebsite: "http://google.com/USA/ADW%202011/Arsenal%202011.pdf" }, { School: "New York 2000", Group: { Name: "New York", ParentGroup: { Name: "USA", ParentGroup: null } }, GroupDisplayText: null, Publisher: "DoE", PublishedDate: "2000", PublishersWebsite: "http://google.com/USA/New York%202000%20Tables.pdf" }],
    result = data.map(({ School, Group: ParentGroup }) => {
        var array = [School];
        while (ParentGroup) {
            array.unshift(ParentGroup.Name);
            ({ ParentGroup } = ParentGroup);
        }
        return array;
    });

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 2

Zohaib Ijaz
Zohaib Ijaz

Reputation: 22885

Use Array.prototype.map and _.get() to handle null scenarios

const data = [{
      "School":"Arsenal 2011",          //4th Element in new array
      "Group":{
         "Name":"Previous",             //3rd Element in new array
         "ParentGroup":{
            "Name":"Arsenal",           //2nd Element in new array
            "ParentGroup":{
               "Name":"USA",            //1st Element in new array
               "ParentGroup":null
            }
         }
      },
      "GroupDisplayText":null,
      "Publisher":"Abbot",
      "PublishedDate":"2011",
      "PublishersWebsite":"http://google.com/USA/ADW%202011/Arsenal%202011.pdf"
   },
   {
      "School":"New York 2000",
      "Group":{
         "Name":"New York",
         "ParentGroup":{
            "Name":"USA",
            "ParentGroup":null
         }
      },
      "GroupDisplayText":null,
      "Publisher":"DoE",
      "PublishedDate":"2000",
      "PublishersWebsite":"http://google.com/USA/New York%202000%20Tables.pdf"
   }];
   
const formatted = data.map(item => {
   return [
     _.get(item, 'Group.ParentGroup.ParentGroup.Name'),
     _.get(item, 'Group.ParentGroup.Name'),
     _.get(item, 'Group.Name'),
     _.get(item, 'School')
   ];
});

console.log(formatted);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js" integrity="sha256-VeNaFBVDhoX3H+gJ37DpT/nTuZTdjYro9yBruHjVmoQ=" crossorigin="anonymous"></script>

Upvotes: 2

nageeb
nageeb

Reputation: 2042

If it was only one level deep, [_.pluck()] would work.(https://lodash.com/docs/3.10.1#pluck)

Gets the property value of path from all elements in collection.

From their example:

var users = [
  { 'user': 'barney', 'age': 36 },
  { 'user': 'fred',   'age': 40 }
];

_.pluck(users, 'user');
// => ['barney', 'fred']

For the nested elements, you can accomplish it with a _.forEach()

Iterates over elements of collection invoking iteratee for each element.

Loop through the items and in the iteratee function just add the appropriate elements to their respective arrays.

Upvotes: 0

Related Questions