如何删除具有相同id的两个json对象

时间:2018-04-30 23:36:20

标签: javascript json

如果我的.json文件包含以下内容:

[
         {
                    "id": "1234",
                    "day": "Monday",
                    "course": "Math110",

         },
         {
                    "id": "1234",
                    "day": "Wednesday",
                    "title": "Math110",

         },
         {
                    "id": "1345",
                    "day": "Tuesday",
                    "title": "Economics210",

         }
]

如何删除id为#34; 1234"的所有对象?在Javascript? (注意有两个具有相同ID的对象)

delete["1234"]会有效吗?

5 个答案:

答案 0 :(得分:2)

使用.filter过滤掉数组元素:



const input = [{
    "id": "1234",
    "day": "Monday",
    "course": "Math110",

  },
  {
    "id": "1234",
    "day": "Wednesday",
    "title": "Math110",

  },
  {
    "id": "1345",
    "day": "Tuesday",
    "title": "Economics210",

  }
];
const output = input.filter(({ id }) => id !== '1234');
console.log(output);




答案 1 :(得分:1)

您可以将JSON解析为数组,然后使用Array.prototype.filter获取一个新数组,该数组没有ID为"1234"的对象:



const json = '[{"id":"1234","day":"Monday","course":"Math110"},{"id":"1234","day":"Wednesday","title":"Math110"},{"id":"1345","day":"Tuesday","title":"Economics210"}]';

const result = JSON.parse( json ).filter( obj => obj.id !== "1234" );

console.log( JSON.stringify( result, null, ' '.repeat(8) ) );




答案 2 :(得分:1)

您无法使用delete运算符,因为它位于deleting a property in an object。您实际上想要删除数组中的对象。

使用旧的for循环和Array.splice()



var inputArray = [{
    "id": "1234",
    "day": "Monday",
    "course": "Math110",

  },
  {
    "id": "1234",
    "day": "Wednesday",
    "title": "Math110",

  },
  {
    "id": "1345",
    "day": "Tuesday",
    "title": "Economics210",

  }
];

var deleteId = "1234";

for (var i = 0; i < inputArray.length; i++) {
  if (inputArray[i].id === deleteId) {
    inputArray.splice(i, 1);
    i = i-1;
  }
}

console.log(inputArray);
&#13;
&#13;
&#13;

注意:如果您可以创建另一个数组而不修改现有数组,请使用其他答案中提到的Array.filter()

答案 3 :(得分:1)

您必须通过指定数组中项目的位置来删除:

const arr = [{
    "id": "1234",
    "day": "Monday",
    "course": "Math110",

  },
  {
    "id": "1234",
    "day": "Wednesday",
    "title": "Math110",

  },
  {
    "id": "1345",
    "day": "Tuesday",
    "title": "Economics210",

  }
];
arr.forEach(function(item, i){
  if(item.id == "1234")
    delete arr[i];
});

console.log(arr.filter(j => j))

答案 4 :(得分:1)

您可以使用过滤方法:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

items = [
    {
        "id": "1234",
        "day": "Monday",
        "course": "Math110",

    },
    {
         "id": "1234",
         "day": "Wednesday",
         "title": "Math110",

    },
    {
         "id": "1345",
         "day": "Tuesday",
         "title": "Economics210",

     }
];

items.filter(function(item) { 
   return item.id !== '1234';  
});