javascript - 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
重复数据可以包含在我的分支标签中
谢谢
解决方案
我想你可以这样做:
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
});
});
});
推荐阅读
- java - 如何在 Spring Boot 中捕获来自 Rest Template 的错误响应?
- java - 创建名为“solverManager”的 bean 时出错,通过构造函数参数表示的依赖关系不满足
- mfc - 是否有可在 MFC SDI 应用程序中使用的 SuspendLayout() 和 ResumeLayout() 函数或其等效函数?
- python - 循环之间共享的Python线程状态?
- reactjs - 使用地图反应动态附加
- enigma2 - 错误:找不到符号:方法 rotate()
- javascript - 无法用信息填写字段
- javascript - setQueryData 不使用 React-Query 更新缓存
- javascript - 使用脚本将来自客户端 API 的坐标与 DB 进行比较
- javascript - 如果数组中的所有字符串都匹配,则在 Javascript 中显示匹配的对象