如何将第二个 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'
});
所以分支
重复数据可以包含在我的分支标记中
谢谢
最佳答案
我想你可以做这样的事情:
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
});
});
});
关于Javascript 将数组插入对象内部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53485903/