1

I have an object element and an array element which contains some items of the object.

I would like to delete the items in the object referenced by the array.

var array = ["test1","test2"];

var object =     

   ...
"test1": {
    "na": [
        "t",
        "t-t",
        "t-98",
        "t"
    ]
},
"test2": {
    "python": [
        "jjj"
    ]
}

 ...

When I use

delete object.test1

It works.

However in my case, I want :

for(var  i = 0 ; i < array.length ; i++){
    delete object.array[i];
}

But I got :

object.array is undefined

Any ideas ?

Fiddle

3
  • 1
    it is because your object object does not have a property named array, it is an independent array object, and does not have anything to do with your object object. That is why you get the error. Commented Feb 16, 2016 at 16:55
  • 6
    object.array[i]; should be object[array[i]]. Commented Feb 16, 2016 at 16:55
  • what's the difference between them ? Commented Feb 16, 2016 at 16:58

2 Answers 2

2

Use object[array[i]], object.array does not exist

If you are using lodash or underscore you can also use the _.omit function.

object = _.omit( object, array )

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

Comments

1

You would need to use array object notation.

delete object[array[i]]

Array notation is the only way to retrieve property values if you are indexing using a string value.

Comments

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.