这真让我发疯!
我有一个axios调用,在控制台中返回一个json数组对象-检查!
>(100) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
>0:
id: 54892250
iid: 1001
ref: "master"
sha: "63e3fc014e207dd4e708749cee3e89a1aa416b7d"
created_at: "2020-03-05T18:57:02.793Z"
updated_at: "2020-03-05T19:06:27.651Z"
>user: {id: someuserid, name: "someuser", username: "someusername", state: "active", avatar_url: "https://assets.gitlab-static.net/uploads/-/system/user/avatar/4534925/avatar.png", …}
>environment: {id: 123456, name: "somename", slug: "somename-iw5iqp", external_url: "https://someaddress.com"}
>deployable: {id: someid, status: "success", stage: "deploy", name: "deploy-staging", ref: "master", …}
status: "success"
__proto__: Object
>1: {id: 54804365, iid: 1000, ref: "filter-out-expired-items", sha: "6225d8018c86fa906063aeea5c10c710ddced14c", created_at: "2020-03-05T12:25:18.949Z", …}
>2: {id: 54804175, iid: 999, ref: "master", sha: "aa5e50c50ba95e9b16cbc57fb968bf9075c625b2", created_at: "2020-03-05T12:24:02.284Z", …}
>3: {id: 54801934, iid: 998, ref: "filter-out-expired-items", sha: "4fc2
现在,我需要根据以下结果做两件事:
像这样:
{ "id": id, "ref": ref, "environment": environment.name, "status": status, "tag": deployable.tag, }
我该怎么做呢?
我有一个工作循环,正在获取所有这些的console.log。但是我需要做的是在我提交状态之前连接所有页面(现在已经剥离到以上字段中)。如果尝试了对象副本,则将其推向数组,并使用各种有前途的工具-但我无法使它们中的任何一个起作用:)
因此,总而言之:
循环的相关部分
// Use headers to get the number of pages
const pages = await axios.head(url, options)
.then((response) => response.headers['x-total-pages']);
console.log('pages=', pages); // DEBUG
// Loop through and push them to an array
for (let i = 0; i <= pages; i += 1) {
console.log('i=', i);
options = {
headers: {
'Private-Token': token,
},
params: {
order_by: 'created_at',
sort: 'desc',
per_page: 100,
page: i,
},
};
axios.get(url, options)
.then((result) => { console.log(result.data); })
}
最佳答案
为总结果创建一个数组:
const results = [];
在记录的地方,解析每个单独的结果:
result.data.forEach(item => {
results.push({
id: item.id,
ref: item.ref,
environment: item.environment.name,
status: item.status,
tag: item.deployable.tag
});
});
请注意,使用常规的
for
循环而不是forEach
可能是性能优化。