1

Hi all pretty new to javascript and would love some help on this problem that Im having. Basically what I am trying to do is to delete a single object from my array. The array contains objects as such: y = [{id:group}].

I would like to delete an object using the object's id, which is the first column.

What I have tried is to loop through the array to find the corresponding id and delete it, but the problem here is that the first column is not labelled "id", the first column is in id form (e.g 123).

Any help would be appreciated.

y = [{123:1},{321:2},{234:3}]
id = 123;

  for (var i = 0; i < y.length; i++)
    if (y[i].id === id) {
      y.splice(i,1);
    }
//Does not work because the first column of the object is not named "id"
2
  • 1
    Dynamic property names are great if you know what they're going to be, but you don't. A more useful object structure would be {id: 123, group: 1} Commented Jul 1, 2017 at 13:30
  • @James Took your advice and decided to recreate my object structure. The solutions here dont work anymore but the array is now easier to work with. Thanks! Commented Jul 2, 2017 at 8:51

3 Answers 3

4

You can use filter instead of a loop:

var y = [{123:1},{321:2},{234:3}]
var id = 123;

y = y.filter((obj) => !obj.hasOwnProperty(id));

console.log(y);

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! This worked really well. Could you tell me what is the benefit of using filter compared to using a loop?
@user 3702643 its syntactic sugar. Using loops is faster and does not recreate the array from the ground of...
The performance is roughly the same, and the code becomes more readable. Another advantage is the functional aspect of it, as you can assign the filtered array to another variable, not having side-effect
2

Just check for that certain key:

for (var i = 0; i < y.length; i++)
  if (key in y[i]) {
    y.splice(i,1);
  }
}

1 Comment

I did go with your loop method in the end because performance was better and it made more sense to me even though the filter method looked cleaner. Thanks!
1

I make a function using two arguments (the array, the key of the object) Using forEach method inside the array I check and compare the the key given key (via argument) with an existen key in the object elements.If it is true then I use splice() method to remove the object contains the key:

y = [{123:1},{321:2},{234:3}];

function deleteObj(arg,value){
  arg.forEach(function(element){       
    var index=arg.indexOf(element);    
    if(Object.keys(element)==value.toString()){
      arg.splice(index,1);
    }
  });
}
deleteObj(y,123);

console.log(y);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.