【发布时间】:2021-06-02 10:20:12
【问题描述】:
我有一个返回带有项目的 JSON 的 API,我在 VUEJS 中接收 JSON。然后我将数据反映在一个 vfor 元素中,但是,有很多重复的键。
所以我想删除 JSON 数组中具有重复主键的对象,例如:
{
{
"id" : 1,
"name": "test"
},
{
"id" : 2,
"name": "other name"
},
{
"id" : 1,
"name": "does not have to be the same name"
},{
"id" : 3,
"name": "but they could be the same"
},{
"id" : 2,
"name": "other name"
},
}
在上面的示例中,我想删除 ID 已经存在的所有对象,结果如下:
{
{
"id" : 1,
"name": "test"
},
{
"id" : 2,
"name": "other name"
}{
"id" : 3,
"name": "but they could be the same"
}
}
我过去尝试过以下JS代码但无济于事:
axios.get(path)
.then((res) => {
this.inv = res.data.descriptions;
for (let i = 0; i < this.inv.length; i += 1) {
Object.entries(this.inv[i]).forEach((key1, value1) => {
Object.entries(this.inv[i]).forEach((key2, value2) => {
if (key1 === 'instanceid' && key2 === 'instanceid') {
if (value1 === value2) {
delete this.inv[i];
}
}
});
});
}
})
.catch((error) => {
// eslint-disable-next-line
console.error(error);
});
【问题讨论】:
标签: javascript json vue.js