IT이야기

JS 인덱스개체 배열 및 스플라이스()가 올바른 개체를 제거하지 않음

cyworld 2022. 4. 12. 00:37
반응형

JS 인덱스개체 배열 및 스플라이스()가 올바른 개체를 제거하지 않음

나는 다음과 같은 종류의 물체를 가지고 있다.

"followers": [
        {
            "id": "1be87842-2f7f-4e3b-8fde-9a998feb3a01",
            "bug_id": "4ae2707b-07ef-4e07-95da-77855c67fece",
            "user_id": "e9e81aa2-4994-483d-a3a7-3b88491f1fda",
            "username": "texample1",
            "name": "Test Example1",
            "created_at": "2018-11-27 21:01:42",
            "updated_at": "2018-11-27 21:01:42",
            "deleted_at": null
        },
        {
            "id": "7bd1fa5f-4109-4beb-b53a-fb03a1d23536",
            "bug_id": "4ae2707b-07ef-4e07-95da-77855c67fece",
            "user_id": "e9e81aa2-4994-483d-a3a7-3b88491f1fda",
            "username": "texample1",
            "name": "Test Example2",
            "created_at": "2018-11-27 21:01:48",
            "updated_at": "2018-11-27 21:01:48",
            "deleted_at": null
        }
    ]

내 vuex 저장소에 다음 코드가 있는 인덱스로 개체 하나를 제거하려고 시도 중:

  let followersArray = state.bugs.find(b => b.id === follower.bug_id).followers
  let index = followersArray.indexOf(follower)
  followersArray.splice(index, 1)

나는 이 돌연변이에 전체 추종자 물체를 통과시킨 다음, 버그 물체에서 팔로워 배열을 찾아 지수를 찾아내고, 전체 버그 물체의 팔로워 배열을 분리하려고 시도하고 있다.이 코드는 버그에서 또 다른 팔로워를 제거한다.지수는 -1로 기록되고 1이어야 한다.내가 뭘 놓쳤는지 아는 사람?만약 내가 정확한 색인을 얻을 수 있다면, 나는 또한 추가 할 것이다.if(index !== -1))저 안에

당신은 사용할 수 있다.findIndex()id를 기반으로 followers의 인덱스를 기능하고 반환한다.

      let index = followersArray.findIndex(i => i.id === follower.id);

:

let items = [{
  name: "aaa"
}, {
  name: "bbb"
}, {
  name: "ccc"
}];
let c = {
  name: "ccc"
};
let index = items.findIndex(item => item.name === c.name)

console.log(index)

이 코드를 실행하면-1:

let index = followersArray.indexOf(follower);

그 말은follower객체가 에 포함되어 있지 않음followersArray. ThefollowersArray의 사본을 포함하고 있는 것 같다.follower객체 - 동일한 객체에 대한 참조가 아님.

설사follower개체는 의 개체와 동일한 속성 및 속성 값을 갖는다.followersArray[1]indexOf답례하다-1동일한 물체가 아닌 한

이제 어레이에서 일치하는 속성 값을 가진 개체만 찾으려면(예:id() 그러면 사용할 수 있다.map또는findIndex그렇게 하려면:

let index = followersArray.map(i => i.id).indexOf(follower.id);

콘솔에서 followerArray 결과를 인쇄하는 경우 표시되는 내용올바른 찾기가 배열을 반환하는 경우, 하나의 요소만 반환하더라도 이 요소를 사용하여 시도하십시오.

let followersArray = state.bugs.find(b => b.id === follower.bug_id).followers[0]

참조URL: https://stackoverflow.com/questions/53509422/js-indexof-array-of-objects-and-splice-not-removing-the-correct-object

반응형