-3

Possible Duplicate:
Remove item from object

I have an object like below:

questions = new Object();

questions = {
 "q1":"answer1",
 "q2":"answer2",
 "q3":"answer3",
 "q4":"answer4"
}

How do remove q3 and q4 and still preserve q1 and q1? Please suggest as dynamic approach to this as you can because questions object is populated dynamically and could have different number of items.

I tried using .slice with no luck:

question = "q2";
questions = questions.slice(0, question);
11
  • 3
    Note that the {} syntax actually creates an object, so the questions = new Object(); line is completely redundant. It's redundant anyway because you are overwriting it. Commented Jul 26, 2012 at 19:38
  • Thanks. I'm familiar with delete object However, this doesn't deliver what I'd like to achieve. Basically, I want to remove remaining items from a certain position (or index). Commented Jul 26, 2012 at 19:47
  • 1
    @StillQuestioning: Object properties have no position. Commented Jul 26, 2012 at 19:47
  • 1
    @StillQuestioning object keys are inherently unordered in javascript. They will never have an index or position. Perhaps you want an array instead? Commented Jul 26, 2012 at 19:49
  • 1
    @StillQuestioning: If the keys are such that they're sortable, closest you could come would be to get the keys with Object.keys, sort the Array of keys, then iterate the Array from the desired point forward, removing each property of the object one at a time using delete. Commented Jul 26, 2012 at 19:49

1 Answer 1

5
delete questions.q1;
console.log(questions.q1); // undefined

The delete keyword removes properties from objects. It's different form setting a property to null, it removes the key entirely.

var a = { b: 123 };
console.log(a.b);             // 123
console.log(Object.keys(a));  // ['b']

a.b = null;
console.log(a.b);             // null
console.log(Object.keys(a));  // ['b']

a.b = void 0;
console.log(a.b);             // undefined
console.log(Object.keys(a));  // ['b']

delete a.b;
console.log(a.b);             // undefined
console.log(Object.keys(a));  // []
Sign up to request clarification or add additional context in comments.

2 Comments

If I do a.b = void 0; it wont erase the key. Object.keys(a) will still return ['b']. The value of the key is simply undefined. It doesn't change much at all.
Yeah my bad, I didn't notice them (was only judging the logs). Deleted.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.