0

I was working on a project that involves using pre-loaded data. The goal of this part is to remove an object from json as such:

   var obj = {'objectName0':[object0, object1, object], 'objectName1':[object, object, object], 'objectName2':[object, object, object]}

I'd usually delete an object from it like this:

delete obj[Object.keys(obj)[i]];

The problem however is that I will be looping through it later on using

obj[data[i]].length,

and as we all know this will return "undefined".

another thing that I'd like to note that when I'm trying to remove this object, I do NOT know it's name, that's why I'm using Object.keys();

  • 1
    Where is `data` being populated? You said the names for your `obj` keys are unknown but you are referencing them through `data[i]`. Make sure data is up to date after you have deleted keys from `obj` – Matt Jun 28 '17 at 21:44
  • What are you trying to do/build here? why are you deleting random keys from this object? Are you really dealing with enumerated properties and variables in your production code or is this just as an example? If you do, why don't you use Arrays to store lists of whatever? – Thomas Jun 28 '17 at 22:03

2 Answers2

0

Treat the object as immutable and make a new one minus the key to delete rather than mutating it. You can use _.omit() from underscore. Or make an equivalent helper function.

gvfordo
  • 189
  • 1
  • 9
0

I would suggest making a new object, but not copying that one object as you copy the entire object. For example, say you had the object,

var obj = {
  object1: {...},
  object2: {...},
  object3: {...}
};

And you wanted to delete the object2. Just loop through and say,

var new_obj = {};
for (var i in obj) {
  if (i != object2) {
    new_obj.i = obj.i;
  }
}
notphilphil
  • 386
  • 4
  • 14