Laravel 6 查询所有返回记录时如何按条件新增自定义数组字段


Postman返回响应结果

需求说明
接口返回记录满足 payment_status 字段值为 payment_pending 条件时,需要在 transaction_type: null、repay: true 两个字段之后新增一个数组类型字段。
实现方案
通用逻辑
- 获取原始业务返回数据
- 遍历每条记录做条件判断
- 满足条件的记录按字段顺序重组,在指定位置插入新数组字段即可
Node.js/JavaScript 实现示例
// 原始响应数据 const originRecords = [/* 你的原始数据 */] const processResponse = (records) => { return records.map(item => { if (item.payment_status !== 'payment_pending') return item // 重组对象保证字段顺序 const { transaction_type, repay, ...otherFields } = item return { ...otherFields, transaction_type, repay, // 替换为实际需要的数组字段名和内容 custom_array_field: ['value1', 'value2'] } }) } // 调用后返回处理后的数据 const finalResponse = processResponse(originRecords)
Python 实现示例
def process_response(origin_records): result = [] for item in origin_records: if item.get('payment_status') != 'payment_pending': result.append(item) continue new_item = {} for key, val in item.items(): new_item[key] = val if key == 'repay': # 替换为实际需要的数组字段名和内容 new_item['custom_array_field'] = ['value1', 'value2'] result.append(new_item) return result
内容的提问来源于stack exchange,提问作者Usman Fayyaz
相关产品推荐
相关产品推荐

