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 Answer 1

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)

Sign up to request clarification or add additional context in comments.

2 Comments

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];
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.