0

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

1
  • Try to use Array.reduce, and recursive functions. it may help. Commented Nov 12, 2019 at 19:35

3 Answers 3

2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Hi Zohaib, Thanks for your answer using your method how could I add a Key to each value? Like 'Name':'USA', 'GroupName':'New York'
2

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; }

1 Comment

you can save some chars with ({ ParentGroup } = ParentGroup)
0

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.

1 Comment

Thanks I will try your suggestion

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.