温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-12-21 14:23:53 来源:亿速云 阅读:435 作者:小新 栏目:移动开发

小编给大家分享一下小程序怎么动态增加删除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对象数组有了一定的了解,想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI