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

如何在JavaScript商品对象数组中添加含用户信息的单个评分?

解决方案

你可以给数组里的每个对象新增一个reviewDetails字段,用来存储单条评分的详细信息,包含具体星级(可从原rating提取数字格式方便后续处理)、评分用户名和评论文本。

改造后的数组示例

let myProducts = [
    {
        productName: "Name of the product",
        rating: '5 Stars',
        reviewDetails: {
            starRating: 5,
            reviewer: "用户张三",
            reviewText: "这款商品质量很好,完全符合预期!"
        }
    },
    {
        productName: "Name of the product",
        rating: '4 Stars',
        reviewDetails: {
            starRating: 4,
            reviewer: "用户李四",
            reviewText: "整体不错,细节还有提升空间。"
        }
    },
    {
        productName: "Name of the product",
        rating: '3 Stars',
        reviewDetails: {
            starRating: 3,
            reviewer: "用户王五",
            reviewText: "中规中矩,符合这个价位的水平。"
        }
    },
    {
        productName: "Name of the product",
        rating: '5 Stars',
        reviewDetails: {
            starRating: 5,
            reviewer: "用户赵六",
            reviewText: "多次回购了,性价比很高!"
        }
    },
    {
        productName: "Name of the product",
        rating: '4 Stars',
        reviewDetails: {
            starRating: 4,
            reviewer: "用户孙七",
            reviewText: "包装很用心,物流也快,好评。"
        }
    },
]

批量添加字段的方法

如果需要快速给现有数组的所有对象批量添加基础的reviewDetails字段,可以用Array.map()实现:

// 自动从原rating提取数字星级,生成带详情字段的新数组
myProducts = myProducts.map(product => {
    const starRating = parseInt(product.rating.split(' ')[0]);
    return {
        ...product,
        reviewDetails: {
            starRating,
            reviewer: "", // 可留空后续填充,或设置默认值
            reviewText: ""
        }
    };
});

这样处理后,每个条目既保留了原有的文本格式星级,又新增了结构化的评分详情,能直接展示用户信息和评论文本。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 09:02:59