0

I have next object:

rows = [
  {
    name: "user1",
    previlege: "Filtering"
  },
  {
    name: "user2",
    previlege: "Reportering"
  },
  {
    name: "user3",
    previlege: "Filtering"
  }
]

And another object:

selected = {
  name: "user1",
  previlege: "Filtering"
}

I want filter rows and delete object which matched, so I need to compare them. I tried like this:

rows.filter(function(object) {
  return JSON.stringify(object) !== JSON.stringify(selected);
});

But it doesn`t work. How can I delete this matched object?

7
  • I ran your code in chrome's console and it worked fine. Commented May 18, 2017 at 19:11
  • Are you sure you want to compare through JSON.stringify(), though? If you want to filter out the object with the same name property, but it has a different previlege property, it wouldn't work. Commented May 18, 2017 at 19:14
  • 1
    what did you mean doesn't work? Commented May 18, 2017 at 19:14
  • You could turn an object into a string and then do a string comparison but you could also just compare the name and privilege properties, which would probably be faster and potentially more reliable. Commented May 18, 2017 at 19:16
  • 1
    Are you taking the result in a new variable like var ans=rows.filter? Commented May 18, 2017 at 19:17

1 Answer 1

3

If you want to remove the element from the array you can try to store the result of filter into a new array

newArray = rows.filter(function(object) {
  return JSON.stringify(object) !== JSON.stringify(selected);
});

rows = newArray;
Sign up to request clarification or add additional context in comments.

2 Comments

Or simply rows = rows.filter(...).
yeah that works too, just trying to be more explicit :)

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.