0

I have a javascript object that looks similar to this:

object {
  attribute[1424]1405: 149,
  attribute[1425]1406: 149,
  attribute[1426]1407: 149,
  attribute[1426]1408: 149,
  attribute[1649]2116: 149,
  attribute[1649]2117: 179,
  attribute[1649]2408: 119
}

I'm trying to remove all properties that don't begin with attribute[1649] (stored in a variable called conditionID). Is there some sort of filter, similar to !:contains() that I can run against the object with a delete command?

1 Answers1

2

No, there is not. Just use a regular for in loop:

for (var p in obj) 
    if (!/^attribute\[1649\]/.test(p))
        delete obj[p];

(see How to check if a string "StartsWith" another string? for alternatives to the regex)

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Thanks @Bergi , that works very well when I explicitly state the string to test for. The string I'm trying to test for (attribute[1649] in this example) however, is stored in a variable, which I think is what led me down the path of using `delete`. I'm trying code like this, but am not having any result: `r = "!/" + conditionID + "/.test(p)";` `reg = new RegExp(r, "g");` `delete amounts[reg];` – Josh Burdick Aug 26 '15 at 19:42
  • The `!` operator is not part of the regex, neither are the `/` literal delimiters. Anyway you should not use a regex here (it would require escaping etc), just use one of the solutions in the linked article for dynamic patterns. – Bergi Aug 26 '15 at 19:48