【问题标题】:How to remove element from JSON array如何从 JSON 数组中删除元素
【发布时间】:2013-09-01 01:45:34
【问题描述】:

我是 nodejs 和 mongodb 的新手。我的问题是我有以下类型的 json

{ 
 _id: 199,
 name: 'Rae Kohout',
 scores: [ 
     { type: 'exam', score: 82.11742562118049 },
     { type: 'quiz', score: 49.61295450928224 },
     { type: 'homework', score: 28.86823689842918 },
     { type: 'homework', score: 5.861613903793295 }
 ]
}

在这里,我想比较“作业”类型的分数并删除分数最低的作业。为了解决这个问题,我编写了一些类似的代码

var low = '';
for(var i=0;i<doc.scores.length;i++)
{
 if(doc.scores[i].type == 'homework'){
   if(low == ''){
      low = doc.scores[i].score;
   }
   if( doc.scores[i].score > low ){
     console.log("index for lowest score is " + i);
     low = '';
   }
 }
}

现在我可以找到得分最低的索引,并希望删除该索引处的值。我尝试使用 Array.splice() 方法,但这仅适用于 Array。谁能帮我解决?

【问题讨论】:

  • 您希望最终结果是什么? scores 是一个数组,所以可以在上面使用拼接。

标签: javascript arrays json


【解决方案1】:

像这样使用splice:

doc.scores.splice(index, 1);

【讨论】:

  • +1 这是从数组中删除元素的正确方法。
  • "当使用两个或多个参数 start、deleteCount 和(可选)item1、item2 等调用 splice 方法时,从数组索引 start 开始的数组的 deleteCount 元素将替换为参数item1、item2 等。返回包含已删除元素(如果有)的 Array 对象。" - ecma-international.org/ecma-262/5.1/#sec-15.4.4.12
  • 如果要移动到另一个json变量怎么办??
【解决方案2】:

splice() 方法通过删除现有元素和/或添加新元素来更改数组的内容。

如果你想从索引 3 中删除 1 个元素。试试这个

var myArray = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon'];
var removed = myArray.splice(3, 1);

// removed is ["mandarin"]
// myArray is ["angel", "clown", "drum", "sturgeon"]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-14
    • 2022-06-11
    • 2021-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多