JavaScript:如何从对象内的对象数组中获取含UserId、CategoryId的值
解决方案
你可以通过遍历specialUser数组,将每个数组元素与外层对象的UserId和CategoryId合并,得到每个元素都包含这两个字段的新数组。以下是具体实现:
JavaScript 示例
假设你的原始对象名为data,代码如下:
const data = { UserId: '634a336122b4b995d25869d5', CategoryId: '620015b6f61454403daba1b4', specialUser: [{ "startDate": "2022-10-3", "endDate": "2022-11-3", "priceType": 1, "price": 199 },{ "startDate": "2022-10-3", "endDate": "2022-11-3", "priceType": 1, "price": 199 },{ "startDate": "2022-10-3", "endDate": "2022-11-3", "priceType": 1, "price": 199 }] }; // 生成包含目标字段的新数组 const result = data.specialUser.map(item => ({ ...item, // 保留原元素的所有属性 UserId: data.UserId, CategoryId: data.CategoryId })); console.log(result);
执行后,result中的每个元素都会包含startDate、endDate、priceType、price、UserId和CategoryId六个字段。
Python 示例(后端场景可用)
若使用Python处理,代码如下:
data = { 'UserId': '634a336122b4b995d25869d5', 'CategoryId': '620015b6f61454403daba1b4', 'specialUser': [ {"startDate": "2022-10-3", "endDate": "2022-11-3", "priceType": 1, "price": 199}, {"startDate": "2022-10-3", "endDate": "2022-11-3", "priceType": 1, "price": 199}, {"startDate": "2022-10-3", "endDate": "2022-11-3", "priceType": 1, "price": 199} ] } # 处理得到目标列表 result = [] for item in data['specialUser']: merged_item = item.copy() merged_item['UserId'] = data['UserId'] merged_item['CategoryId'] = data['CategoryId'] result.append(merged_item) print(result)
内容的提问来源于stack exchange,提问作者user20219125
相关产品推荐
相关产品推荐

