programing

JavaScript 관련 배열에서 개체를 삭제하려면 어떻게 해야 합니까?

randomtip 2022. 9. 23. 21:38
반응형

JavaScript 관련 배열에서 개체를 삭제하려면 어떻게 해야 합니까?

다음 코드가 있다고 가정합니다.

var myArray = new Object();
myArray["firstname"] = "Bob";
myArray["lastname"] = "Smith";
myArray["age"] = 25;

, '을 '성'에 하는 것이 요?myArray["lastname"].remove()

(요소의 수가 중요하기 때문에 청결하게 유지하고 싶기 때문에 요소를 제거해야 합니다.)

JavaScript의 오브젝트는 키(속성)를 값에 매핑하는 연관 배열로 생각할 수 있습니다.

JavaScript 개체에서 속성을 제거하려면 연산자를 사용합니다.

const o = { lastName: 'foo' }
o.hasOwnProperty('lastName') // true
delete o['lastName']
o.hasOwnProperty('lastName') // false

<> 님의 경우:delete는 의 인덱스 속성에 적용되며, 희박하게 채워진 배열(즉, 누락된 인덱스가 있는 배열)을 만듭니다.

의 인스턴스를 Array, 、 populated array - - - - - - - - - - - -(일반적으로 작성하지 않는 경우) 또는 를 사용해야 합니다.

에 주의:delete자바스크립트그 목적은 객체에서 속성을 제거하는 것입니다.에 대한 하고 있는 o , , , 「 」o이후 일반 방법으로 가비지가 수집됩니다.

「 」의 delete 연산자는 JavaScript 엔진의 코드 최적화 기능에 영향을 줄 수 있습니다.

JavaScript의 모든 객체는 해시 테이블/관련 배열로 구현됩니다.예를 들어 다음과 같습니다.

alert(myObj["SomeProperty"]);
alert(myObj.SomeProperty);

앞서처럼 '제거'를 '를 하는 delete키워드: 두 가지 방법으로 사용할 수 있습니다.

delete myObj["SomeProperty"];
delete myObj.SomeProperty;

추가 정보가 도움이 되길...

중 것도 .JavaScript에는 어소시에이트 어레이가 .array라고 입력합니다.를 참조해 주세요.

JavaScript에는 동적 속성을 가진 객체 인스턴스가 있습니다.속성이 Array 개체 인스턴스의 요소와 혼동되면 Bad Things™가 발생합니다.

문제

var elements = new Array()

elements.push(document.getElementsByTagName("head")[0])
elements.push(document.getElementsByTagName("title")[0])
elements["prop"] = document.getElementsByTagName("body")[0]

console.log("number of elements: ", elements.length)   // Returns 2
delete elements[1]
console.log("number of elements: ", elements.length)   // Returns 2 (?!)

for (var i = 0; i < elements.length; i++)
{
   // Uh-oh... throws a TypeError when i == 1
   elements[i].onmouseover = function () { window.alert("Over It.")}
   console.log("success at index: ", i)
}

솔루션

폭발하지 않는 범용 제거 기능을 사용하려면 다음을 사용하십시오.

Object.prototype.removeItem = function (key) {
   if (!this.hasOwnProperty(key))
      return
   if (isNaN(parseInt(key)) || !(this instanceof Array))
      delete this[key]
   else
      this.splice(key, 1)
};

//
// Code sample.
//
var elements = new Array()

elements.push(document.getElementsByTagName("head")[0])
elements.push(document.getElementsByTagName("title")[0])
elements["prop"] = document.getElementsByTagName("body")[0]

console.log(elements.length)                        // Returns 2
elements.removeItem("prop")
elements.removeItem(0)
console.log(elements.hasOwnProperty("prop"))        // Returns false as it should
console.log(elements.length)                        // returns 1 as it should

이렇게 하면 개체만 삭제되지만 어레이 길이는 그대로 유지됩니다.

요소를 배열에서 제거하려면 다음과 같은 작업을 수행해야 합니다.

array.splice(index, 1);

인정된 답변은 맞지만, 왜 효과가 있는지에 대한 설명은 누락되어 있습니다.

우선, 코드는, 이것이 어레이가 아니라는 사실을 반영할 필요가 있습니다.

var myObject = new Object();
myObject["firstname"] = "Bob";
myObject["lastname"] = "Smith";
myObject["age"] = 25;

오브젝트를 포함한다)에 해 주세요.Array할 수 .s)ㄹ 수 있습니다. 표준 함수가 오브젝트 .

이렇게 '어느끼다,느끼다,느끼다,느끼다,느끼다,느끼다,느끼다,느끼다,느끼다,느끼다.delete「 」 、 「 」 、 「 」 。

delete myObject["lastname"]

오브젝트(관련 배열/사전)를 사용하거나 어레이(맵)를 사용할 경로를 결정해야 합니다.절대 둘 다 섞지 마세요.

Airbnb Style Guide에는 이를 위한 우아한 방법이 있습니다(ECMAScript 7).

const myObject = {
  a: 1,
  b: 2,
  c: 3
};
const { a, ...noA } = myObject;
console.log(noA); // => { b: 2, c: 3 }

저작권: https://codeburst.io/use-es2015-object-rest-operator-to-omit-properties-38a3ecffe90

다른 답변에서 알 수 있듯이 JavaScript 배열이 아니라 JavaScript 개체를 사용하고 있습니다.이 개체는 모든 키가 문자열로 변환되는 것을 제외하고 다른 언어의 연관 배열과 거의 동일하게 작동합니다. 맵은 키를 원래 유형으로 저장합니다.

개체가 아닌 배열이 있는 경우 배열의 .filter 함수를 사용하여 제거할 항목 없이 새 배열을 반환할 수 있습니다.

var myArray = ['Bob', 'Smith', 25];
myArray = myArray.filter(function(item) {
    return item !== 'Smith';
});

이전 브라우저와 jQuery를 사용하는 경우 jQuery는 다음과 같은 방식으로 작동합니다.

myArray = $.grep(myArray, function(item) {
    return item !== 'Smith';
});

메서드 「」를 합니다.splice오브젝트 배열에서 항목을 완전히 삭제하려면:

Object.prototype.removeItem = function (key, value) {
    if (value == undefined)
        return;

    for (var i in this) {
        if (this[i][key] == value) {
            this.splice(i, 1);
        }
    }
};

var collection = [
    { id: "5f299a5d-7793-47be-a827-bca227dbef95", title: "one" },
    { id: "87353080-8f49-46b9-9281-162a41ddb8df", title: "two" },
    { id: "a1af832c-9028-4690-9793-d623ecc75a95", title: "three" }
];

collection.removeItem("id", "87353080-8f49-46b9-9281-162a41ddb8df");

개체를 사용 중이고 처음부터 연결된 배열이 없습니다.관련지어 어레이에서는 다음과 같이 아이템 추가 및 삭제가 이루어집니다.

    Array.prototype.contains = function(obj)
    {
        var i = this.length;
        while (i--)
        {
            if (this[i] === obj)
            {
                return true;
            }
        }
        return false;
    }


    Array.prototype.add = function(key, value)
    {
        if(this.contains(key))
            this[key] = value;
        else
        {
            this.push(key);
            this[key] = value;
        }
    }


    Array.prototype.remove = function(key)
    {
        for(var i = 0; i < this.length; ++i)
        {
            if(this[i] == key)
            {
                this.splice(i, 1);
                return;
            }
        }
    }



    // Read a page's GET URL variables and return them as an associative array.
    function getUrlVars()
    {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

        for(var i = 0; i < hashes.length; i++)
        {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }

        return vars;
    }


    function ForwardAndHideVariables() {
        var dictParameters = getUrlVars();

        dictParameters.add("mno", "pqr");
        dictParameters.add("mno", "stfu");

        dictParameters.remove("mno");


        for(var i = 0; i < dictParameters.length; i++)
        {
            var key = dictParameters[i];
            var value = dictParameters[key];
            alert(key + "=" + value);
        }
        // And now forward with HTTP-POST
        aa_post_to_url("Default.aspx", dictParameters);
    }


    function aa_post_to_url(path, params, method) {
        method = method || "post";

        var form = document.createElement("form");

        // Move the submit function to another variable
        // so that it doesn't get written over if a parameter name is 'submit'
        form._submit_function_ = form.submit;

        form.setAttribute("method", method);
        form.setAttribute("action", path);

        for(var i = 0; i < params.length; i++)
        {
            var key = params[i];

            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", params[key]);

            form.appendChild(hiddenField);
        }

        document.body.appendChild(form);
        form._submit_function_(); // Call the renamed function
    }

보다 기능적이고 우아한 접근방식을 원하는 경우 다음을 수행할 수 있습니다.

const o = { firstName: "foo", lastName: "bar" };
const { lastName, ...removed } = o;
lastName // bar
removed // { firstName: "foo" }

「」의 .removed개체에 항목이 남아 있지 않으면 정의되지 않습니다.

항목을 명시적으로 '정의되지 않음'에 할당하여 지도에서 항목을 제거할 수 있습니다.고객님의 경우와 마찬가지로:

myArray["성"] = 정의되지 않았습니다.

어떤 이유로든 삭제 키가 작동하지 않는 경우(내게 작동하지 않는 것처럼), 삭제 키를 분리한 다음 정의되지 않은 값을 필터링할 수 있습니다.

// To cut out one element via arr.splice(indexToRemove, numberToRemove);
array.splice(key, 1)
array.filter(function(n){return n});

스플라이스는 제거된 요소를 반환하므로 체인을 시도하지 마십시오.

키워드를 사용하면 JavaScript의 배열에서 배열 요소가 삭제됩니다.

예를들면,

다음 문장을 검토해 주십시오.

var arrayElementToDelete = new Object();

arrayElementToDelete["id"]           = "XERTYB00G1";
arrayElementToDelete["first_name"]   = "Employee_one";
arrayElementToDelete["status"]       = "Active";

delete arrayElementToDelete["status"];

코드의 마지막 행은 키가 "status"인 어레이 요소를 어레이에서 삭제합니다.

기능으로도 사용할 수 있습니다.Angular는 프로토타입으로 사용할 경우 일부 오류를 발생시킵니다.@HarpyWar 감사합니다.그것은 내가 문제를 해결하는데 도움이 되었다.

var removeItem = function (object, key, value) {
    if (value == undefined)
        return;

    for (var i in object) {
        if (object[i][key] == value) {
            object.splice(i, 1);
        }
    }
};

var collection = [
    { id: "5f299a5d-7793-47be-a827-bca227dbef95", title: "one" },
    { id: "87353080-8f49-46b9-9281-162a41ddb8df", title: "two" },
    { id: "a1af832c-9028-4690-9793-d623ecc75a95", title: "three" }
];

removeItem(collection, "id", "87353080-8f49-46b9-9281-162a41ddb8df");

프로젝트에 Underscore.js 의존관계가 있는 경우는 매우 간단합니다.

_.omit(myArray, "lastname")

나에게 유일한 작업 방법은 다음과 같습니다.

function removeItem (array, value) {
    var i = 0;
    while (i < array.length) {
        if(array[i] === value) {
            array.splice(i, 1);
        } else {
            ++i;
        }
    }
    return array;
}

사용방법:

var new = removeItem( ["apple","banana", "orange"],  "apple");
// ---> ["banana", "orange"]

'어레이'의 경우:

인덱스를 알고 있는 경우:

array.splice(index, 1);

값을 알고 있는 경우:

function removeItem(array, value) {
    var index = array.indexOf(value);
    if (index > -1) {
        array.splice(index, 1);
    }
    return array;
}

에 대한 가장 높은 응답delete오브젝트에서는 정상적으로 동작하지만 실제 어레이에서는 동작하지 않습니다.사용하는 경우delete루프에서 요소를 제거하지만 요소는 그대로 유지합니다.empty배열의 길이는 변경되지 않습니다.이것은 시나리오에 따라서는 문제가 될 수 있습니다.

예를 들어 myArray에서 myArray.toString()을 삭제한 후delete빈 엔트리가 생성됩니다.,,.

var myArray = newmyArray = new Object();
myArray["firstname"] = "Bob";
myArray["lastname"] = "Smith";
myArray["age"] = 25;

var s = JSON.stringify(myArray);

s.replace(/"lastname[^,}]+,/g, '');
newmyArray = JSON.parse(p);

루프/반복하지 않고 동일한 결과를 얻을 수 있습니다.

언급URL : https://stackoverflow.com/questions/346021/how-do-i-remove-objects-from-a-javascript-associative-array

반응형