0

How do I create the data array from my second api call result into the format I want? I have a code like this

var github = require('octonode');
var client = github.client();
var userName = "octocat";
var repoName = "";
var branchName = "";
var data = [];
var branches = [];

client.get('/users/'+userName+'/repos', {}, function (err, status, body, headers) {
  body.forEach(function(obj) {
    repoName = obj.name;
    //==============================
      client.get('repos/'+userName+'/'+repoName+'/branches', {}, function (errx, statusx, bodyChild, headersx) {
      bodyChild.forEach(function(objChild) {
        branchName = objChild.name;
          });
      });
    });
});

I have received repoName and branchName data as well.

I want my data format like

enter image description here

How to use

data.push({
   name: repoName,
   branches: 'branchName loooping here for every repoName'
});

so branches repetition data can be contained in my branches tag

Thank you

2
  • You need to push into the inner array. Commented Nov 26, 2018 at 17:07
  • hi @SLaks can you give me some example? Commented Nov 26, 2018 at 17:19

2 Answers 2

1

I guess you can do something like this:

var data = [];

client.get('/users/'+userName+'/repos', {}, function (err, status, body, headers) {
  body.forEach(function(obj) {
    repoName = obj.name;
    client.get('repos/'+userName+'/'+repoName+'/branches', {}, function (errx, statusx, bodyChild, headersx) {
        let elem = {"name": repoName, "branches": []}; //create json object for each repo 
        bodyChild.forEach(function(objChild) {
          elem.branches.push(objChild.name); //push all branchs to that elem
        });
        data.push(elem); // add the elem to the data array
      });
    });
});
Sign up to request clarification or add additional context in comments.

2 Comments

Hi @David, when I try your code the result is empty when I check console.log(data);
My mistake...sorry Thanks @David
0

So in this case data is an object, that has a property name which is string, and another property branches which is array. If you want to push data to the property branches you can just call the push() function on it.

Please check the example below:

    let data = {
        name: "repoName",
        branches: [
            {
                name: "foo"
            }
        ]
    }

    data.branches.push(
        {
            name: "bar"
        }
    );

    console.log(data);

Comments

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.