0

I need a help regarding flattening an array which contains array of Objects.

I have tried my luck with flat(), lodash flatten, But couldn't help

Example: -
[
  [
    {
      name : 'a'
    },
    {
      name : 'b'
    }
   ],
   [
    {
      name : 'c'
    },
    {
      name : 'd'
    }
   ]
] 

Here is the code: - I am using Promise.all() instead of normal request inside for loop I get arrays of JSON data and all promises which are resolved are pushed in an array thus creating nested Array with array of JSON objects

const request = require('request-promise')
var fs = require('fs');
let ps = []
let i,n
var requests = require("request");
var _ = require('lodash')
// var options = {
//   method: 'GET',
//   url: 'http://api.github.com/orgs/samsung',
//   headers:
//   {
//     'cache-control': 'no-cache',
//     Connection: 'keep-alive',
//     Referer: 'http://api.github.com/orgs/samsung',
//     'Accept-Encoding': 'gzip : true, deflate',
//     Cookie: '_octo=GH1.1.1825524242.1563990727; logged_in=no',
//     'Postman-Token': '3a69f2c3-5762-478a-8178-7d7fef971c1a,38ad48f7-291f-43eb-be81-286d433d8928',
//     'Cache-Control': 'no-cache',
//     Accept: '*/*',
//     Authorization: 'Basic U2lkZGhhbnRCb2hyYTpjaHJvbWl1bTM2MA==',
//     'User-Agent': 'PostmanRuntime/7.15.2'
//   },
//   json: true
// };


// requests(options,(error ,response,body) =>{
//   console.log(body)
//   n = body.public_repos
//   if (n % 100 == 0) {
//     n = n / 100
//     console.log('size',n)
//   }
//   else {
//     n = parseInt((n / 100) + 1)
//     console.log('size',n)
//   }
//  })

  for (i = 0; i < 2; i++) {
    var val = {
      method: 'GET',
      url: `https://api.github.com/orgs/samsung/repos`,
      qs: { per_page: '100', page: i.toString() },
      headers:
      {
        'cache-control': 'no-cache',
        Connection: 'keep-alive',
        'Accept-Encoding': 'gzip : true',
        Cookie: '_octo=GH1.1.1825524242.1563990727; logged_in=no',
        Host: 'api.github.com',
        'Postman-Token': 'db984097-df9c-4140-b98a-f9f70c135dbe,4bd1ce88-2405-40b2-8be9-87de92978ccf',
        'Cache-Control': 'no-cache',
        Accept: '*/*',
        'User-Agent': 'PostmanRuntime/7.15.2',
        Authorization: 'Basic U2lkZGhhbnRCb2hyYTpjaHJvbWl1bTM2MA=='
      },
    };
    ps.push(request(val))
  };
  // request(options).then(response => {
  //     let data = JSON.parse(response)
  //   //  res.send(JSON.parse(response));
  // }).catch(err =>{
  //     res.send(err);
  // })

Promise.all(ps).then( result => {
  console.log(result.length)
  if (Array.isArray(result)) {
    console.log("We got an array")
    // for(let l = 0; l < result.length;l++)
    // {
    //   for(let m = 0; m < result[l][0].length; m++)
    //   {
    //     data.push(result[l][m])
    //   }
    // }
     data = result.flat(2)
  }
  fs.writeFile('./output.json', data, 'utf-8', error => {
    console.log('file is ready')
  })

}).catch(err => {
  console.log(err)
})

I tried flat() and lodash-flatten, still got same thing after writing contents to a file

Click here to Download the file

Community
  • 1
  • 1
  • Possible duplicate of [How to merge two arrays in JavaScript and de-duplicate items](https://stackoverflow.com/questions/1584370/how-to-merge-two-arrays-in-javascript-and-de-duplicate-items) – Webber Jul 26 '19 at 06:25
  • What do you expect to see after flattening? [{"name":"a"},{"name":"b"},{"name":"c"},{"name":"d"}]? That is what you get using flat(). – MofX Jul 26 '19 at 06:30
  • This is Just an example, JSON object is quite large and its from the API response,I used array.flat(), still no result from it – Siddhant Bohra Jul 26 '19 at 06:46
  • I have added the File, Please have a look – Siddhant Bohra Jul 26 '19 at 07:05

1 Answers1

1

flat(): Parameters

depth | Optional

The depth level specifying how deep a nested array structure should be flattened. Defaults to 1.

You can specify the depth up to which you want to flatten your array:

var arr = [
  [
    {
      name : 'a'
    },
    {
      name : 'b'
    }
   ],
   [
    {
      name : 'c'
    },
    {
      name : 'd'
    }
   ]
];
var res = arr.flat(2);
console.log(res);
Mamun
  • 66,969
  • 9
  • 47
  • 59