摘要:对象中的属性赋值,数组行的转换为对象
说明:setData 函数用于改变对应的 this.data,同时将数据从逻辑层发送到视图层。所以每setdata一次赋值会引发界面刷新一次。从性能上考虑,修改数据时,应一次性setdata批量改变。另一种方式是直接赋值只会改变数据,不会影响界面的刷新。
开发微信小程序,我为什么放弃 setData,使用 upData
https://www.jb51.net/article/167827.htm
创建对象的方式
 var basicInfo = new {
      barCode: '',
      categoryId: 0,
      characteristic: '',
      commission: 0,
      commissionType: 0,
      dateAdd: Date,
      dateStart: Date,
      dateUpdate: Date,
      id: Schema.Types.ObjectId,
      logisticsId: 0,
      minPrice: 0,
      minScore: 0,
      name: '',
      numberFav: 0,
      numberGoodReputation: 0,
      numberOrders: 0,
      originalPrice: 0,
      paixu: 0,
      pic: '',
      pingtuan: Boolean,
      pingtuanPrice: 0,
      propertyIds: '',
      recommendStatus: 0,
      recommendStatusStr: '',
      shopId: 0,
      status: 0,
      statusStr: '',
      stores: 0,
      userId: 0,
      videoId: '',
      views: 0,
      weight: 0,
    }1.场景:给对象中的属性赋值
1.1 js
// miniprogram/pages/admin/productCategory/index/index.js
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    productCategory: {
      Appid: app.globalData.appid,
      Openid: app.globalData.openId,
      Unionid: app.globalData.unionid,
      IsRoot: true,
      CategoryId: '',
      ParentId: '',
      Name: '测',
      PictureId: '',
      DisplayOrder: 0,
      CreatedOnUtc: '',
      UpdatedOnUtc: '',
      Published: true,
      Deleted: false,
    },
   
    productCategorys:[],
    isEditStatus: false, // 是否在编辑状态
  },
1.2.xml
<form bindsubmit="bindSave">
    <view class="form-box">
      <view class="row-wrap">
        <view class="label">分类名称</view>
        <view class="label-right">
          <input style='display:none' data-value='{{id}}' name="id" value='{{productCategory._id}}'></input>
        
          <input data-value='{{Name}}' name="Name" value='{{productCategory.Name}}' placeholder="请输入分类名称"></input>
      
        </view>
      </view>
    </view>
    <button type="warn" class="save-btn" formType="submit">提交</button>
    <button type="default" class="cancel-btn" bindtap="bindCancel">取消</button>
  </form>1.3.对象赋值
bindSave: function (e) {
    var that = this;
    let { productCategory } = e.detail.value;
    this.setData({
      
      ['productCategory.Name']:e.detail.value.Name,
     
    })
    console.log('form发生了submit事件,携带数据为:', e.detail.value);
   
   this.onCreate();
  },
给对象中中的子对象的赋值
{
  "Appid": null,
  "AuthorOpenid": null,
  "AuthorUnionid": null,
  "OriginalId": null,
  "Sku": null,
  "Name": null,
  "OrderNumber": null,
  "ProducTypeId": null,
  "ProducType": {
    "Name": null,
    "IsDeleted": false,
    "CreatedOnUtc": "0001-01-01T00:00:00",
    "UpdatedOnUtc": "0001-01-01T00:00:00",
    "_id": null
  },
  "Quantity": 1,
  "Price": 0,
  "ProductStockOutDate": "2020-09-13T14:23:15.3874435Z",
  "Mark": null,
  "WarehouseId": null,
  "Warehouse": {
    "Name": null,
    "IsDeleted": false,
    "CreatedOnUtc": "0001-01-01T00:00:00",
    "UpdatedOnUtc": "0001-01-01T00:00:00",
    "_id": null
  },
  "ShippingAddress": {
    "Appid": null,
    "AuthorOpenid": null,
    "AuthorUnionid": null,
    "OriginalId": null,
    "CustomerId": null,
    "FirstName": null,
    "LastName": null,
    "Email": null,
    "Company": null,
    "VatNumber": null,
    "CountryId": null,
    "StateProvinceId": null,
    "City": null,
    "Address1": null,
    "Address2": null,
    "ZipPostalCode": null,
    "PhoneNumber": null,
    "FaxNumber": null,
    "CustomAttributes": null,
    "CreatedOnUtc": "0001-01-01T00:00:00",
    "UserName_zh_CN": null,
    "Mobile1": null,
    "Mobile2": null,
    "Mobile": [],
    "InstalledOnUtc": "0001-01-01T00:00:00",
    "_id": null
  },
  "IsDeleted": false,
  "LastloginIP": null,
  "CreatedOnUtc": "0001-01-01T00:00:00",
  "UpdatedOnUtc": "0001-01-01T00:00:00",
  "_id": null
}
step 1.先将对象ShippingAddress取出来
let shippingAddress = that.data.ProductStockForShop.ShippingAddress;step 2:赋值
//客户信息
    shippingAddress.UserName_zh_CN = e.detail.value.UserName_zh_CN;
    shippingAddress.Mobile1 = e.detail.value.Mobile1;
    shippingAddress.Mobile2 = e.detail.value.Mobile2;
    shippingAddress.Address1 = e.detail.value.Address1;
 step 3:填回去
 
    //填回去
    productStockForShop.ShippingAddres = shippingAddress;
var that = this;
    let isEditStatus = that.data.isEditStatus;
    //对象赋值
    let productStockForShop = that.data.ProductStockForShop;
    let shippingAddress = that.data.ProductStockForShop.ShippingAddress;
    console.log(configCollection.ProductStockForShop + "编辑后的记录内容", configCollection.ProductStockForShop)
    const db = wx.cloud.database() //打开数据库连接
    //---直接对data赋值,不会引起界面刷新---
    productStockForShop.Appid = app.globalData.appid;
    productStockForShop.OriginalId = app.globalData.minappOrigalid;
    productStockForShop.AuthorUnionid = app.globalData.unionid;
    productStockForShop.AuthorOpenid = app.globalData.openid;
    productStockForShop.OrderNumber = e.detail.value.OrderNumber;
    productStockForShop.Warehouse = that.data.ProductStockForShop.Warehouse;
    productStockForShop.ProducType = that.data.ProductStockForShop.ProducType;
    productStockForShop.Quantity = parseInt(e.detail.value.Quantity);
    productStockForShop.Price = parseFloat(e.detail.value.Price);
    productStockForShop.ProductStockOutDate = that.data.ProductStockForShop.ProductStockOutDate;
    productStockForShop.Mark = e.detail.value.Mark;
    //客户信息
    shippingAddress.UserName_zh_CN = e.detail.value.UserName_zh_CN;
    shippingAddress.Mobile1 = e.detail.value.Mobile1;
    shippingAddress.Mobile2 = e.detail.value.Mobile2;
    shippingAddress.Address1 = e.detail.value.Address1;
    //填回去
    productStockForShop.ShippingAddres = shippingAddress;
2.数组中包行对象的操作

如上图所示,在this.data中设置ceshi这条数据,在方法中,我们定义ceshi变量让其等于that.data.ceshi; 然后对ceshi进行操作,其实就是对that.data.ceshi进行操作,而that.setData({ceshi})就等同于that.setData({ceshi : ceshi }) ; 第一个ceshi 是that.data.ceshi, 第二个ceshi 是我们定义的变量ceshi。通过打印的结果可以看到,数据已经添加上了
3.对象转换成对象数组

我们应该转化为数组对象 [{},{},{},{}] ,最后通过wx:for遍历到页面

小程序:怎么向对象里添加数组,向数组里添加对象?
var arr=[];
var obj={};
let str = { "addtime": '1543021769' };
var arr1 = [ 'a','b','c','c' ];向数组里添加元素:arr.push(str)
向对象里添加元素,首先得设置属性名,如:obj.arr1 = arr1
小程序之数组操作:push与concat
push 遇到数组参数时,把整个数组参数作为一个元素;
concat 则是拆开数组参数,一个元素一个元素地加进去。 
push 直接改变当前数组;concat 不改变当前数组。
arr1=arr1.concat(arr2)
var arr = [];
arr.push(1);
arr.push(2);
arr.push([3, 4])
arr.push(5, 6);
arr = arr.concat(7);
arr = arr.concat([8, 9]);
arr = arr.concat(10, 11);
for(var i in arr){
  console.log(i+"-----"+arr[i]);
}打印结果如下:
index.js [sm]:180 0-----1
index.js [sm]:180 1-----2
index.js [sm]:180 2-----3,4
index.js [sm]:180 3-----5
index.js [sm]:180 4-----6
index.js [sm]:180 5-----7
index.js [sm]:180 6-----8
index.js [sm]:180 7-----9
index.js [sm]:180 8-----10
index.js [sm]:180 9-----11
小程序页面间的对象传递
https://blog.csdn.net/wahyip/article/details/80982351
数组修改
Page({
  /**
   * 页面的初始数据
   */
  data: {
    
    stockIndex: {
      min_time: [],
      last_px: [],
      avg_px: [],
      BA_color: [],
      business_amount: [],
      shanghaiCompositeIndex: [] //SSE (Shanghai Stock Exchange) Composite Index; 上海证券交易所指数;
    },修改:先删除最后一个,然后再添加一个
 //---开始计算大盘指数涨幅 end----
      if (prev_min_time === current_min_time)
      {
        shanghaiCompositeIndex.pop();
      }
      shanghaiCompositeIndex.push(preStockClose + preStockClose * radio); 动态新增对象属性的功能
        this.setData({
          report: res.m_kdReport,
          "report.color": "ft-green",
          reportList: reportList,
        })为report object对象新增一个颜色值
微信小程序js数组倒序reverse
普通.js用法
var a = [1,2,3]; //创建数组·
alert(a.reverse()); //颠倒顺序并输出
输出结果321
微信小程序.js用法
var a = [1,2,3]; //创建数组·
console.log(a.reverse()); //颠倒顺序并输出
5.常见错误
5.1 小程序给object对象赋值出现Setting data field "productCategory.Name" to undefined is invalid
测试情况:
运行正确
that.setData({
     
      
      ["productCategory.Name"]: "e.detail.value.Name",
    })运行出现错误:Setting data field "productCategory.Name" to undefined is invalid.
that.setData({
      
      
      ["productCategory.Name"]: e.detail.value.Name,
    })出现这种情况的时候是页面setData 的时候,e.detail.value.Name没有获取到值,然后就会将undefined给productCategory.Name字段,此时默认字段就会变成undefined,那么就会出现这种问题,解决方法就是 setData的时候判断获取到的值是否存在,不存在的时候给定一个默认值即可
数组对象中每个对象添加一个字段
方法一 使用Array map()方法
方法二 使用Array forEach()方法
  this.data.WarehouseList.forEach((value, index) => {
      value['sex'] = 'men'
    })https://blog.csdn.net/qq_37582010/article/details/100017958
方法三 直接修改数组
var warehouseList = this.data.WarehouseList;
    for (var i = 0, lenI = warehouseList.length; i < lenI; ++i) {
      warehouseList[i].checked = true;
    }
    this.setData({
      WarehouseList: warehouseList,
    });
  
对象判断为空值
 if (JSON.stringify(app.globalData.Employee) == "{}") {
