首页 > 解决方案 > Javascript在对象内推送数组

问题描述

如何将我的第二个 api 调用结果创建为我想要的格式的数据数组?我有这样的代码

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

我也收到了repoName数据branchName

我想要我的数据格式

在此处输入图像描述

如何使用

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

所以branches重复数据可以包含在我的分支标签中

谢谢

标签: javascriptarrays

解决方案


我想你可以这样做:

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

推荐阅读