Asked  7 Months ago    Answers:  5   Viewed   34 times

I have an array of objects like so:

var myArray = [
    {field: 'id', operator: 'eq', value: id}, 
    {field: 'cStatus', operator: 'eq', value: cStatus}, 
    {field: 'money', operator: 'eq', value: money}
];

How do I remove a specific one based on its property?

e.g. How would I remove the array object with 'money' as the field property?

 Answers

76

One possibility:

myArray = myArray.filter(function( obj ) {
    return obj.field !== 'money';
});

Please note that filter creates a new array. Any other variables referring to the original array would not get the filtered data although you update your original variable myArray with the new reference. Use with caution.

Tuesday, June 1, 2021
 
astaykov
answered 7 Months ago
86

something like this perhaps:

function remove_adjacent_dups($arr) {
  $prev = null;
  $result = array();
  foreach( $arr as $val ) {
    if( $val !== $prev ) array_push($result, $val);
    $prev = $val;
  }
  return $result;
}
Wednesday, March 31, 2021
 
Sagar
answered 9 Months ago
46

I wrote a function for you, trying to make it as pretty and reusable as possible :

function setProp(path, newValue, holder) {
    var t = path.split(/[[]"]+/).filter(function(v){return v}),
        l = t.pop(), s, o = holder || window;
    while (s = t.shift()) o = o[s];
    o[l] = newValue;
}

You use it like this :

setProp('root["obj1"]["obj2"]', 2);

If your root object isn't in a global variable, pass the relevant holder as third argument.

Demonstration (open the console to see the changed root object)

Saturday, August 7, 2021
 
Gabriele
answered 4 Months ago
62

Using the comment by @gurvinder372 as influence, you should do the following:

myArray.sort(function (a, b) {
  var textA = a.name.toUpperCase();
  var textB = b.name.toUpperCase();

  return textA.localeCompare(textB);
});
Thursday, September 2, 2021
 
mfro
answered 3 Months ago
12

You can use typeof operator.

if( (typeof A === "object" || typeof A === 'function') && (A !== null) )
{
    alert("A is object");
}

Note that because typeof new Number(1) === 'object' while typeof Number(1) === 'number'; the first syntax should be avoided.

Monday, September 13, 2021
 
Wilk
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share