简体   繁体   中英

Delete object items from an array

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

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 )

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM