规格数据处理

发布时间 2023-10-11 14:17:01作者: zjxgdq
 const data = [
    {
      productSpecsName: '内存',
      specificationBindingDTOList: [{ sttrValue: '128' }, { sttrValue: '258' }]
    },
    {
      productSpecsName: '颜色',
      specificationBindingDTOList: [{ sttrValue: '白色' }]
    },
    {
      productSpecsName: '大小',
      specificationBindingDTOList: [{ sttrValue: '1' }, { sttrValue: '20' }]
    }
  ];

  function processData(data:any, result:any = {}, currentIndex = 0, currentObj:any = {}) {
    const currentSpec = data[currentIndex];
    const { productSpecsName, specificationBindingDTOList } = currentSpec;

    specificationBindingDTOList.forEach((spec:any) => {
      const { sttrValue } = spec;

      currentObj[productSpecsName] = sttrValue;

      if (currentIndex === data.length - 1) {
        result[JSON.stringify(currentObj)] = { ...currentObj };
      } else {
        processData(data, result, currentIndex + 1, { ...currentObj });
      }
    });

    return Object.values(result);
  }

  const result = processData(data);
  console.log(result);