0

I have the following Javascript object

var datasets = [];

datasets.push({
    DataItem1: {
        label: "My Title",
        data: [[9], [11]]
    },
    DataItem2: {
        label: "Another title",
        data: [[139], [3], [0], [1]]
    },
    DataItem3: {
        label: "My Label",
        data: [[1], [3]]
    }
});

I would like to remove an item, based upon a second list. However, I'll only know the label value

This is what I've tried so far

var labelsToExclude = [];

labelsToExclude.push("Another title");

var myDataSet = datasets[0];
var dataToUse=[];

for (x in myDataSet) {
    var dataItemLabel = myDataSet[x].label;
    if (labelsToExclude.indexOf(dataItemLabel) < 0) {       
        delete myDataSet.x
    }   
}   
dataToUse.push(myDataSet);

As you can see, I started with 3 items in my object, I'd expect there to only be 2 after this code was run.

Can some one explain what I've done wrong, I have read How do I remove a property from a JavaScript object? and it didn't help.

Community
  • 1
  • 1
MyDaftQuestions
  • 4,487
  • 17
  • 63
  • 120

1 Answers1

4

You are trying to delete "x" from myDataSet, not the current item from the for in loop

delete myDataSet.x

should be

delete myDataSet[x];
epascarello
  • 204,599
  • 20
  • 195
  • 236
  • So simple, this is perfect, thank you for taking the time and wearing an excellent hat in your avatar. – MyDaftQuestions Feb 20 '14 at 14:37
  • 2
    @AshishMishra, I know the rules here, but, as I'm sure you know, there is a time lapse before I can do it. You'll also notice I've accepted every question I've posted so it should have been clear I know how the system works! I also don't know why you feel you need to police this, but up to you I guess... – MyDaftQuestions Feb 20 '14 at 14:43