programing

자바 스크립트 연관 배열에서 객체를 어떻게 제거합니까?

nasanasas 2020. 10. 3. 10:54
반응형

자바 스크립트 연관 배열에서 객체를 어떻게 제거합니까?


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

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

이제 "성"을 제거하려면? ....과 동등한 것이
myArray["lastname"].remove()있습니까?

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


Javascript에서 "delete"키워드를 사용하십시오.

delete myArray["lastname"];

편집하다:

일부 JavaScript 엔진에서 delete 키워드는 컴파일 / JIT 최적화를 취소하므로 성능이 저하 될 수 있습니다.

http://www.html5rocks.com/en/tutorials/speed/v8/ http://www.smashingmagazine.com/2012/11/writing-fast-memory-efficient-javascript/


JavaScript의 모든 객체는 해시 테이블 / 연관 배열로 구현됩니다. 따라서 다음은 동일합니다.

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

그리고 이미 언급 delete했듯이 키워드 를 통해 객체에서 속성을 "제거"합니다 . 두 가지 방법으로 사용할 수 있습니다.

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

추가 정보가 도움이되기를 바랍니다.


이전 답변 중 어느 것도 Javascript가 시작하는 연관 배열이 없다는 사실을 다루지 않습니다 . array유형 이 없습니다 typeof.을 참조하십시오 .

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;

모든 객체 ( Arrays 포함 )는이 방법으로 사용할 수 있습니다. 그러나 표준 JS 배열 함수 (pop, push, ...)가 객체에서 작동 할 것이라고 기대하지 마십시오!

수락 된 답변에서 말했듯이 delete객체에서 항목을 제거하는 데 사용할 수 있습니다 .

delete myObject["lastname"]

원하는 경로를 결정해야합니다. 객체 (연관 배열 / 사전)를 사용하거나 배열 (맵)을 사용합니다. 두 가지를 섞지 마십시오.


메서드 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");

Object를 사용하고 있으며 시작하는 연관 배열이 없습니다. 연관 배열의 경우 항목 추가 및 제거는 다음과 같습니다.

    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
    }

As other answers have noted, what you are using is not a Javascript array, but a Javascript object, which works almost like an associative array in other languages except that all keys are converted to strings. The new Map stores keys as their original type.

If you had an array and not an object, you could use the array's .filter function, to return a new array without the item you want removed:

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

If you have an older browser and jQuery, jQuery has a $.grep method that works similarly:

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

There is an elegant way in Airbnb Style Guide to do this (ES7):

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

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


If for whatever reason the delete key is not working (like it wasnt working for me )

You can splice it out and then filter the undefined values

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

Dont try and chain them since splice returns removed elements;


You can remove an entry from your map by explicitly assigning it to 'undefined'. As in your case:

myArray["lastname"] = undefined;


Its very straight forward if you have underscore.js dependency in your project -

_.omit(myArray, "lastname")

We can use it as a function too. Angular throws some error if used as a prototype. Thanks @HarpyWar. It helped me solve a problem.

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");

By using the "delete" keyword, it will delete the array element from array in javascript.

For example,

Consider following statements.

var arrayElementToDelete = new Object();

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

delete arrayElementToDelete["status"];

Last line of the code will remove the array element who's key is "status" from the array.


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);

Without looping/iterates we get the same result


For "Arrays":

If you know the index:

array.splice(index, 1);

If you know the value:

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

The most upvoted answer for delete works well in case of objects but not for the real arrays. If I use delete it removes elements from loops but keeps the element as empty and length of array wont change. This may be a problem in some scenarios.

For example, if I do myArray.toString() on myArray after removal via delete it creates empty entry i.e. ,,


The only working method for me:

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

usage:

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

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

반응형