Giuan Adauto Giuan Adauto - 2 months ago 6
Javascript Question

javascript - Whats the best way of deleting a object on a array

I want to delete a object on my objects array, but i cant find a better way than using some loop to do such a thing, on each object we have an ID

example:

var array = [{
id : String,
price : Number,
someOtherVars : String
}]

var element = {
id : "00dks",//this is a unic value
price : 12,
someOtherVars : "some value"
}

var element2 = {
id : "a43sdk",
price : 30,
someOtherVars : "some value"
}

var element3 = {
id : "0as0d",
price : 122,
someOtherVars : "some value"
}
array.push(element);
array.push(element2);
array.push(element3);


so... what is the most efficient way of doing this?

ps: i'm looking for a way to access the element by the key with out using any kind of loop, like the function .find(), example
array["0as0d"]
, to get element3

Answer

Don't use an array, but a Map.

var map = new Map();

var element = {
    id         : "00dks",//this is a unic value
    price      : 12,
    someOtherVars : "some value"    
}

var element2 = {
    id         : "a43sdk",
    price      : 30,
    someOtherVars : "some value"    
}

var element3 = {
    id         : "0as0d",
    price      : 122,
    someOtherVars : "some value"    
}
map.set(element.id, element);
map.set(element2.id, element2);
map.set(element3.id, element3);

// later... 

if (map.delete("0as0d")) {
  console.log('delete successful');
}

console.log(map.size);

Comments