JS使用属性数组移除多维数据属性



基本上我有一个对象,它将是多维的,属性可以命名为任何名称,它可以有许多维度。

在某个时候,我需要在这个对象中附加/拼接一个属性,来自不知道它位置的代码。

因此,一个示例对象:

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

我需要拼接data.locations.data[1],我唯一的信息是下面的数组和索引。显然,我知道第一个属性将是response

['locations','data']
index: 1

编辑:

我的错误,data属性的数组值不是对象!

您可以使用Array#reduce()并传入obj.response作为起始值,以获取嵌套的父级,根据显示的数组,该父级将是obj.response.locations.data

然后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)

最新更新