Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.0k views
in Technique[技术] by (71.8m points)

给后端传的参数名和长度不固定怎么办?

一个修改商品价格的接口
order_goods[0][order_goods_id]order_goods[0[change_price]这两个参数名和长度不固定 如果同时修改多个商品价格 那么字段名是根据下标来命名的 如果修改3个商品价格就根据下标来写参数名 就像下面写的这样 参数名不能写死了 也不确定传多少个参数 这种情况怎么办呢? 如果我每次用test里面的数据来传参应该怎么写呢?
ps.这种命名参数的方法是不是不好?我总感觉后端是故意为难我

let test = [
    {
        id: 34546,
        price: 55
    },
    {
        id: 14124,
        price: 99
    },
    {
        id: 96558,
        price: 44
    }
]

下面是写死的参数

let obj = {
      order_id: this.data.changeList.id,
      confirmchange: 'yes',
      dispatch_price: 55,
      'order_goods[0][order_goods_id]': 1114,
      'order_goods[0][change_price]': 41,
      'order_goods[1][order_goods_id]': 1120,
      'order_goods[1][change_price]': 69,
      'order_goods[2][order_goods_id]': 1115,
      'order_goods[2][change_price]': 50,
    }
api.common_post('admin/shop?c=site&a=entry&m=yun_shop&do=4410&route=order.change-order-price.store',obj).then(res=>{
      console.log(res)
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

遍历 test 生成所需的参数对象然后 merge 到 obj 里。

let obj = {
    ...Object.fromEntries(
        test.reduce((prev, cur, idx) => {
            prev.push([`order_goods[${idx}][order_goods_id]`, cur.id]);
            prev.push([`order_goods[${idx}][change_price]`, cur.price]);

            return prev;
        }, [])
    ),
    // 其他属性
    // ...
};

Object.fromEntries(),就是 Object.entries() 的一个逆操作。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...