Josh Burdick
Josh Burdick

Reputation: 37

Deleting javascript object properties not matching a string

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?

Upvotes: 0

Views: 1110

Answers (1)

Bergi
Bergi

Reputation: 664559

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)

Upvotes: 2

Related Questions