拼接数组Javascript中的对象

时间:2016-04-11 23:47:28

标签: javascript arrays

如果某个键的特定值与给定字符串匹配,我试图从数组中删除一个对象:

示例数据:

array = [{_id: "abc", test: "123"}, 
         {_id: "def", test: "123"},
         {_id: "ghi", test: "123"}];

这是我的循环:

for (var i = 0; i < array.length; i++) {
    var x = "123"
    if (array[i].test == x) {
       array.splice(i, 1)
    }
}

这应该返回一个空数组,但它会在数组中留下一个对象(最后一个)并且我不知道为什么。

4 个答案:

答案 0 :(得分:4)

如果删除元素,则不得增加i

假设数组有两个匹配元素。

第一次迭代,i = 0

i ==>>  element 1
        element 2

然后删除元素1,并递增i

        element 2
i ==>>   

有很多方法可以解决这个问题。这是一个用for循环取代while循环的示例。

var i = 0;
while (i < array.length) {
    var x = "123"
    if (array[i].test == x) {
       array.splice(i, 1)
    } else {
       ++i;
    }
}

答案 1 :(得分:1)

想出来:

array = array.filter(function(array) {
  var x = "123";
  return array.test !== x;
})

答案 2 :(得分:0)

我编写了一个函数,该函数从html中获取索引和事件值,并在ts中进行处理

app.component.html

<tr *ngFor="let container of containers; let i = index;" 
      [(ngModel)]="miningname"
            ngDefaultControl>
              <td>
    <input *ngIf="addMore" type="text" class = "form-control" 
     placeholder="Key" 
     [(ngModel)]="container.key2Name" 
       (ngModelChange)="textKeyChangedMore($event,i)">
</td></tr>

app.component.ts

  textKeyChangedMore(eventMore, indexMore) {


    var valueLength = this.selectedAPIName.length

      var i = indexMore+1;
      if (this.selectedAPIName[i].value == undefined ) {

        this.selectedAPIName.splice(indexMore + 1, 1, { key: eventMore, value: undefined });
      }
      else if (this.selectedAPIName[i].value !== undefined) {

        this.selectedAPIName.splice(indexMore + 1, 1, { key: eventMore, value: this.selectedAPIName[i].value });
      }
}

答案 3 :(得分:0)

array = [
  {id: "abc", test: "123"}, 
  {id: "def", test: "456"},
  {id: "ghi", test: "789"}
];
let x = "123";
let i = array.findIndex(data => data.test === x);
    if (i !== -1) {
        array.splice(i, 1);
    } else ...
console.log(array);