[英]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. 我需要拼接出
data.locations.data[1]
,我唯一的信息是下面的数组和索引。 Obviously I will know the first property will be response
. 显然,我知道第一个属性将是
response
。
['locations','data']
index: 1
Edit: 编辑:
My mistake, the data
property has an array value not an object! 我的错误,
data
属性具有数组值而不是对象!
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
. 您可以使用
Array#reduce()
并传入obj.response
作为起始值,以获取嵌套父级,该父级基于显示的数组为obj.response.locations.data
。
Then splice()
the indexed item in that parent or do whatever other modifications are needed 然后
splice()
该父项中的索引项或进行任何其他必要的修改
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.