如何在循环中删除嵌套的JS对象?

时间:2017-07-13 09:00:38

标签: javascript jquery arrays function

我试图在属性与我的参数匹配时删除特定对象(此时轮子的名称是"米其林")但我无法使其工作..

我怎么能这样做?



var car = {
  type: "Fiat",
  model: "500",
  color: "White",
  wheels: [{
    name: "Goodyear",
    color: "Red"
  }, {
    name: "Goodyear",
    color: "Yellow"
  }, {
    name: "Goodyear",
    color: "Black"
  }, {
    name: "Michelin",
    color: "Blue"
  }]
};

$.each(car.wheels, function() {
  if (this.name == "Michelin") {
    delete this;
  }
})
console.log(car);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:4)

$.each方法的回调函数有两个参数:

$.each(car.wheels, function(i,item) {
   if (item.name == "Michelin") {
       delete car.wheels[i];
   }
});

但这 最佳解决方案。通常,delete运算符用于从对象删除属性。如果你在数组上使用它,删除将删除数组项,但不会重新索引数组或更新其长度。这使它看起来好像是未定义的:

&#13;
&#13;
var car = {
      type: "Fiat",
      model: "500",
      color: "White",
      wheels: [{
        name: "Goodyear",
        color: "Red"
      }, {
        name: "Goodyear",
        color: "Yellow"
      }, {
        name: "Goodyear",
        color: "Black"
      }, {
        name: "Michelin",
        color: "Blue"
      }]
};
$.each(car.wheels, function(i,item) {
    if (item.name == "Michelin") {
       delete car.wheels[i];
    }
});
console.log(car);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

解决方案是使用filter方法接受回调提供的函数应用于数组中的每个项目。

&#13;
&#13;
var car = {
      type: "Fiat",
      model: "500",
      color: "White",
      wheels: [{
        name: "Goodyear",
        color: "Red"
      }, {
        name: "Goodyear",
        color: "Yellow"
      }, {
        name: "Goodyear",
        color: "Black"
      }, {
        name: "Michelin",
        color: "Blue"
      }]
 };
car.wheels=car.wheels.filter(function(wheel){
  return wheel.name!='Michelin';
});
console.log(car);
&#13;
&#13;
&#13;

答案 1 :(得分:1)

使用jQuery grep功能:

&#13;
&#13;
var car = {
  type: "Fiat",
  model: "500",
  color: "White",
  wheels: [{
    name: "Goodyear",
    color: "Red"
  }, {
    name: "Goodyear",
    color: "Yellow"
  }, {
    name: "Goodyear",
    color: "Black"
  }, {
    name: "Michelin",
    color: "Blue"
  }]
};
car.wheels= $.grep(car.wheels,function(wheel){
  return wheel.name!='Michelin';
});
console.log(car);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
&#13;
&#13;
&#13;