0

I'm trying to delete a number of items from an object using some kind of wildcard. The object could look like this:

myObject = {
    id_0: {...},
    id_1: {...},
    id_2_radio_0: {...},
    id_2_radio_1: {...},
    id_2_radio_2: {...},
    id_5: {...},
    id_21: {...}
}

And the I would like to be able to do something like this (pseudo code):

delete myObject['id_2_' + *] 

so it would delete all elements with a key starting with "id_2_"

Is there a reasonable way to do this? Either that or collecting an array of all the keys that match my wildcard and the foreaching through that array deleting every element.

I hope I'm not too confusing in my description of my problem!

Here's a sample of the real JSON:

{
    "jy-id-1_radio_0":{ "label":"alternativ 1", "reference":"jy-id-1" },
    "jy-id-1_radio_1":{ "label":"alternativ 2", "reference":"jy-id-1" },
    "jy-id-2":{ "label":"kryssruta", "reference":"jy-id-2" },
    "jy-id-3":{ "label":"kryssruta", "reference":"jy-id-3" }
}
Christoffer
  • 7,470
  • 9
  • 39
  • 55

1 Answers1

3

You could iterate the keys and delete if the string starts with a given pattern.

var object = {
  id_0: {},
  id_1: {},
  id_2_radio_0: {},
  id_2_radio_1: {},
  id_2_radio_2: {},
  id_5: {},
  id_21: {}
};

Object.keys(object).forEach(function (k) {
    if (k.startsWith('id_2_')) {
        delete object[k];
    }
});

console.log(object);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392