IT이야기

axios 응답 개체의 모든 항목에서 vuex 상태로 특정 값을 추출하려면 어떻게 해야 합니까?

cyworld 2022. 6. 3. 22:37
반응형

axios 응답 개체의 모든 항목에서 vuex 상태로 특정 값을 추출하려면 어떻게 해야 합니까?

미치겠네!

콘솔에서 json 어레이 개체를 반환하는 Axios 호출이 있습니다. - 확인하세요!

>(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

이제 이 결과를 위해 두 가지 작업을 수행해야 합니다.

  1. 완전히 확장되었을 때 이 응답은 크고 수천 개의 응답도 있습니다.vuex 상태에서 1000s의 자이언트 json 응답을 저장하는 대신 먼저 다음과 같은 값만 추출합니다.
    • 아이디
    • 레퍼런스
    • environment.name
    • 상황
    • deployable.tag

예를 들어 다음과 같습니다.

{ "id": id, "ref": ref, "environment": environment.name, "status": status, "tag": deployable.tag, }

이거 어떻게 해?

  1. 이 응답은 위의 여러 페이지에 걸쳐 페이지화되어 있으며, 한 페이지 결과의 일부에 불과합니다.

나는 그것을 위한 작동 루프를 가지고 있고 모든 것에 대한 console.log를 받고 있다.그러나 내가 해야 할 일은 모든 페이지를 연결하는 것이다(현재 위의 필드로 제거됨).오브젝트 카피, 어레이 및 모든 종류의 유틸리티에의 푸시를 시도했지만, 어느 것도 동작하지 않는 경우:)

요약하면 다음과 같습니다.

  1. 한 페이지 결과를 얻다
  2. 배열 내의 항목을 간이 버전으로 스쿼시하다
  3. 그것들을 모두 내가 그 주에 삽입할 수 있는 물체로 모아라.

루프의 관련 부분

  // 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.

Promise를 사용하여 요청 순서를 유지할 수 있을 것 같습니다.따라서 여러 페이지에 걸쳐 정렬 데이터를 사용할 수 있습니다.중요한 것은 각 Axios 호출을 배열에 배치한 다음 호출하는 것입니다.Promise.all([])해당 어레이를 사용하여 요청을 수행한 원래 순서로 모든 응답을 한 번에 가져옵니다.

// 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

let promises = [];

// 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,
    },
  };

  let promise = axios.get(url, options);
  // this below keep responses order
  promises.push(promise);
}

// This wait for all Axios calls to be resolved as promise
Promise.all(promises)
  .then((result) => {
    // now if you have 10 pages, you'll have result[0] to result[9], each of them is an axios response
    console.log(result[0].data);
    console.log(result[1].data); // if pages > 0

    let items = []; // you can declare it outside too for Scope access
    for (let i = 0; i <= pages; i += 1) {
      // so many records, then take the minimum info
      if (result[i].data.length >= 1000) {
        result[i].data.forEach(item => {
          items.push({
            id: item.id,
            ref: item.ref,
            environment: item.environment.name,
            status: item.status,
            tag: item.deployable.tag
          });
        }
      } else {
        // Not so many records then take all info
        items = items.concat(result[i]);
      }
    }

    // TODO: do whatever you want with the items array now

  });

여기서는 원래 개체를 속성 중 일부만 있는 단순 개체로 매핑합니다.

const newResult = result.data.map(d => ({
                                   id: d.id,
                                   ref: d.ref,
                                   environmentName: d.environment.name,
                                   status: d.deployable.status,
                                   deployableTag: d.deployable.tag
                                 }))

const data = [
  {
    "created_at": "2016-08-11T07:36:40.222Z",
    "updated_at": "2016-08-11T07:38:12.414Z",
    "deployable": {
      "commit": {
        "author_email": "admin@example.com",
        "author_name": "Administrator",
        "created_at": "2016-08-11T09:36:01.000+02:00",
        "id": "99d03678b90d914dbb1b109132516d71a4a03ea8",
        "message": "Merge branch 'new-title' into 'master'\r\n\r\nUpdate README\r\n\r\n\r\n\r\nSee merge request !1",
        "short_id": "99d03678",
        "title": "Merge branch 'new-title' into 'master'\r"
      },
      "coverage": null,
      "created_at": "2016-08-11T07:36:27.357Z",
      "finished_at": "2016-08-11T07:36:39.851Z",
      "id": 657,
      "name": "deploy",
      "ref": "master",
      "runner": null,
      "stage": "deploy",
      "started_at": null,
      "status": "success",
      "tag": false,
      "user": {
        "id": 1,
        "name": "Administrator",
        "username": "root",
        "state": "active",
        "avatar_url": "http://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80&d=identicon",
        "web_url": "http://gitlab.dev/root",
        "created_at": "2015-12-21T13:14:24.077Z",
        "bio": null,
        "location": null,
        "public_email": "",
        "skype": "",
        "linkedin": "",
        "twitter": "",
        "website_url": "",
        "organization": ""
      },
      "pipeline": {
        "created_at": "2016-08-11T02:12:10.222Z",
        "id": 36,
        "ref": "master",
        "sha": "99d03678b90d914dbb1b109132516d71a4a03ea8",
        "status": "success",
        "updated_at": "2016-08-11T02:12:10.222Z",
        "web_url": "http://gitlab.dev/root/project/pipelines/12"
      }
    },
    "environment": {
      "external_url": "https://about.gitlab.com",
      "id": 9,
      "name": "production"
    },
    "id": 41,
    "iid": 1,
    "ref": "master",
    "sha": "99d03678b90d914dbb1b109132516d71a4a03ea8",
    "user": {
      "avatar_url": "http://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80&d=identicon",
      "id": 1,
      "name": "Administrator",
      "state": "active",
      "username": "root",
      "web_url": "http://localhost:3000/root"
    }
  },
  {
    "created_at": "2016-08-11T11:32:35.444Z",
    "updated_at": "2016-08-11T11:34:01.123Z",
    "deployable": {
      "commit": {
        "author_email": "admin@example.com",
        "author_name": "Administrator",
        "created_at": "2016-08-11T13:28:26.000+02:00",
        "id": "a91957a858320c0e17f3a0eca7cfacbff50ea29a",
        "message": "Merge branch 'rename-readme' into 'master'\r\n\r\nRename README\r\n\r\n\r\n\r\nSee merge request !2",
        "short_id": "a91957a8",
        "title": "Merge branch 'rename-readme' into 'master'\r"
      },
      "coverage": null,
      "created_at": "2016-08-11T11:32:24.456Z",
      "finished_at": "2016-08-11T11:32:35.145Z",
      "id": 664,
      "name": "deploy",
      "ref": "master",
      "runner": null,
      "stage": "deploy",
      "started_at": null,
      "status": "success",
      "tag": false,
      "user": {
        "id": 1,
        "name": "Administrator",
        "username": "root",
        "state": "active",
        "avatar_url": "http://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80&d=identicon",
        "web_url": "http://gitlab.dev/root",
        "created_at": "2015-12-21T13:14:24.077Z",
        "bio": null,
        "location": null,
        "public_email": "",
        "skype": "",
        "linkedin": "",
        "twitter": "",
        "website_url": "",
        "organization": ""
      },
      "pipeline": {
        "created_at": "2016-08-11T07:43:52.143Z",
        "id": 37,
        "ref": "master",
        "sha": "a91957a858320c0e17f3a0eca7cfacbff50ea29a",
        "status": "success",
        "updated_at": "2016-08-11T07:43:52.143Z",
        "web_url": "http://gitlab.dev/root/project/pipelines/13"
      }
    },
    "environment": {
      "external_url": "https://about.gitlab.com",
      "id": 9,
      "name": "production"
    },
    "id": 42,
    "iid": 2,
    "ref": "master",
    "sha": "a91957a858320c0e17f3a0eca7cfacbff50ea29a",
    "user": {
      "avatar_url": "http://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80&d=identicon",
      "id": 1,
      "name": "Administrator",
      "state": "active",
      "username": "root",
      "web_url": "http://localhost:3000/root"
    }
  }
]

const result = data.map(d => ({
  id: d.id,
  ref: d.ref,
  environmentName: d.environment.name,
  status: d.deployable.status,
  deployableTag: d.deployable.tag
}))

console.log(result)

언급URL : https://stackoverflow.com/questions/60582335/how-can-i-extract-specific-values-from-all-items-in-axios-response-object-to-a-a

반응형