Ra3IDeN Ra3IDeN - 18 days ago 5
Javascript Question

How to filter array that has item with the same name but diffirent value?

I have an array that has items in it.

I make this array through collecting form data with this function:

getFormdata : function(form) {
var formdata = $(form)
.serializeArray()
.filter(function (item) {
return item.name != "__RequestVerificationToken"
});

return formdata;
}


When I have a checkbox in the form and when it is checked I get two items in the array where one has the value


true


and the other has


false


I am using jquery filter functon to filter the array but I can't figure out how I can discared the item that has the value


false


the undesiered result of the array:

enter image description here

my attempt:

getFormdata : function(form) {
var formdata = $(form)
.serializeArray()
.filter(function (item) {
return item.name != "__RequestVerificationToken" && (item.name == "IsActive" && item.value != "false");
});

return formdata;
}


but this filters out all elements and not just the one I want removed.

How do I do this?

EDIT:

Item nr 2 should only be removed if there are two items with the same name.
If i have ONLY one item with the name "IsActive" then nr 2 should not be removed

Answer

If two "IsActive" exists, remove the false one. Otherwise, leave it alone. Added the removal of the validation token. Moved the check for value != "false" before the second filter to possibly short circuit the conditional and gain performance.

var test = [
  { name: "__RequestVerificationToken", value: "whatever" },
  { name: "IsActive", value: "true" },
  { name: "updateRate", value: "sss" },
  { name: "IsActive", value: "false" },
  { name: "somethingElse", value: "weee" }
];

console.log(test.filter(function(element, index, array){
  return  element.name != "__RequestVerificationToken" && (
            element.value != "false"
            || array.filter(function(element2){
              return element2.name == element.name
            }).length < 2
          );
}));

var test = [
  { name: "__RequestVerificationToken", value: "whatever" },
  { name: "updateRate", value: "sss" },
  { name: "IsActive", value: "false" },
  { name: "somethingElse", value: "weee" }
];

console.log(test.filter(function(element, index, array){
  return  element.name != "__RequestVerificationToken" && (
            element.value != "false"
            || array.filter(function(element2){
              return element2.name == element.name
            }).length < 2
          );
}));