You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在多键值对中查找值并构建产品统一输出数组

解决方案:统一处理成功与失败产品数据

要把混合了成功产品和失败产品集合的原始数据转换成统一格式的数组,你可以按以下逻辑处理:

核心思路

  1. 遍历原始数组,区分两种元素:
    • 带product_id的是成功产品,直接给它加一个空的error字段
    • 带failed_products的是失败产品集合,需要逐个处理里面的每个失败产品
  2. 处理失败产品的错误信息:
    • 提取每个失败产品里所有非空的错误文本
    • 用" and "连接多个错误,作为error字段的值
    • 补充product_name字段(按示例设为空字符串)

代码实现(JavaScript)

const originalData = [
  { "product_name": "", "product_id": "1" },
  { "product_name": "", "product_id": "2" },
  {
    "failed_products": [
      { "product_id": "3", "attribute_1": "Error in value: attribute_1", "attribute_2": "" },
      { "product_id": "4", "attribute_1": "Error in value: attribute_1", "attribute_2": "Error in value: attribute_2" }
    ]
  }
];

const finalResult = [];

originalData.forEach(item => {
  // 处理成功创建的产品
  if (item.product_id) {
    finalResult.push({
      ...item,
      error: ""
    });
  }
  // 处理失败产品集合
  else if (item.failed_products) {
    item.failed_products.forEach(failedProduct => {
      // 过滤出所有有效的错误信息(跳过空值和product_id)
      const errorMessages = Object.values(failedProduct)
        .filter(val => val && val.includes("Error in value:"));
      // 合并多个错误信息
      const combinedError = errorMessages.join(" and ");
      // 构造符合要求的失败产品对象
      finalResult.push({
        product_name: "",
        product_id: failedProduct.product_id,
        error: combinedError
      });
    });
  }
});

console.log(finalResult);

关键细节说明

  • 用Object.values(failedProduct)获取失败产品的所有属性值,再通过filter筛选出真正的错误文本(避免把product_id或空值当成错误)
  • 如果失败产品本身带有product_name的原始值,可以把product_name: ""改成product_name: failedProduct.product_name || "",兼容更多场景
  • 错误信息的连接符可以根据需求调整,比如换成逗号", "

内容的提问来源于stack exchange,提问作者Marcos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 11:13:20