Tom Tom - 3 months ago 10
jQuery Question

Jquery array find and replace entry on partial match

I have an array like this containing data like : [mode:id:A:B]

eg:

["del:123456789:0:0", "del:99887766:0:0", "edit:1471872633890:8845:0"]


is there anyway I can check and see if there is a partial match on the id and the remove then entry and replace it ?

eg:

match on
1471872633890
and replace the entire entry match with
edit:1471872633890:8845:NE
so the array becomes :

["del:123456789:0:0", "del:99887766:0:0", "edit:1471872633890:8845:NW"]


As an aside... can you serialize an array for ajax posting ?
If not I need to rethink this anyway !

Thanks

UPDATE
I'm trying to update an existing array entry or add a new entry.

This is what I've got...

var id = $(this).closest('tr').find('input[name="id[]"]').val()
var A = $(this).closest('tr').find('input[name="A[]"]').val()
var B = $(this).closest('tr').find('input[name="A[]"]').val()
var res = 'edit:' + id + ':' + A + ':' + B;

filters = filters.map(function(value) {
if( value.indexOf(id) > -1 ) {
return res;
}
return value;
});


How do I actually update the values in the array ?

Answer

I would use map in this case. You can even use another loop, but it is easy to handle in this case and I like the behavior. Just do a search inside and return the new value.

var arr = ["del:123456789:0:0", "del:99887766:0:0", "edit:1471872633890:8845:0"];

arr = arr.map(function(value) {
    if( value.indexOf("1471872633890") > -1 ) {
        return "edit:1471872633890:8845:NW";
    }
  
    return value;
});

console.log(arr);

Or if you like, as for loop:

var arr = ["del:123456789:0:0", "del:99887766:0:0", "edit:1471872633890:8845:0"];

for( var i = 0; i < arr.length; i++ ) {
    if( arr[i].indexOf("1471872633890") > -1 ) {
        arr[i] = "edit:1471872633890:8845:NW";
    }
}

console.log(arr);

If you use jQuery ajax there is no need to serialize the array. You can just send them with the data property.

var arr = ["del:123456789:0:0", "del:99887766:0:0", "edit:1471872633890:8845:0"];

$.ajax({
    url: "foo.php",
    method: "post",
    data: {
        myArray: arr
    }
});