小程序怎么动态增加删除JSON对象数组

小编给大家分享一下小程序怎么动态增加删除JSON对象数组,希望大家阅读完这篇文章后大所收获,下面让我们一起去探讨吧!

先看效果,在制作小程序时,经常遇到类似这种情况:

小程序怎么动态增加删除JSON对象数组

直接上代码:

<view class="add-btn" bindtap='addItems'>添加</view>

<view wx:for="{{itemLists}}" wx:key="index" class='list'>
  <input type='text' value='{{item.id}}'></input>
  <text>{{item.time}}</text>
  <text class='delete-btn' data-idx='{{index}}' bindtap='deleteIitems'>删除</text>
</view>
.add-btn{
  background: chocolate;
  width: 200rpx;
  text-align: center;
  color: white;
  margin-bottom: 10px;
}
.list{
  display: flex;
  justify-content: space-around;
  border: 1px solid;
}
.delete-btn{
  background: red;
}
Page({

  data: {
    itemLists: [
      { id: 1, time: '00:00:00' },
      { id: 2, time: '00:00:00' },
      { id: 3, time: '00:00:00' }
    ]
  },
  addItems() {
    let list = this.data.itemLists
    list.push({ id: ~~(Math.random()*100), time: '00:00:00' })
    this.setData({
      itemLists: list
    })
  },
  deleteIitems(e) {
    let idx = e.currentTarget.dataset.idx
    let list = this.data.itemLists
    let filterRes = list.filter((ele,index) => {
      return index != idx
    })
    this.setData({
      itemLists: filterRes
    })
  }

})

总结:

关键处是使用ES6中的filter过滤方法,删除对象数组中的第几个对象。

过滤更多的时候是用在过滤掉指定的内容。

看完了这篇文章,相信你对小程序怎么动态增加删除JSON对象数组有了一定的了解,想了解更多相关知识,欢迎关注行业资讯频道,感谢各位的阅读!