简体   繁体   中英

JS Remove multi-dimensional data property using array of properties

Basically I have got an object, which will be multi-dimensional and the properties could be named anything and it could have many dimensions.

At some point I will need to append/splice a property within this object, from code which won't know it's position.

So, an example object:

let obj = {
    response: {
        locations: {
            data: [
                0: Object,
                1: Object,
                2: Object,
            ]
        }
    },
    endpoint: null
}

I need to splice out data.locations.data[1] , the only information I have is the below array and the index. Obviously I will know the first property will be response .

['locations','data']

index: 1

Edit:

My mistake, the data property has an array value not an object!

You can use Array#reduce() and pass in obj.response as the start value to get at the nested parent which based on the array shown would be obj.response.locations.data .

Then splice() the indexed item in that parent or do whatever other modifications are needed

 const arr = ['locations','data'], index= 1, obj = { response: { locations: { data: [{id:1},{id:2}, {id:3}] } }, endpoint: null } const targetArr = arr.reduce((a,c)=> (a[c]), obj.response); targetArr.splice(index,1); console.log(obj) 

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