javascript - 如何在对象数组Javascript中添加随机值?
问题描述
const prod = [{
name: "Sweat",
description: " collection",
price: 150,
},
{
name: "Trousers",
description: "Attire",
price: 243
},
{
name: "T-shirt",
description: "Winter",
},
{
name: "Hoody",
description: "Fashion",
},
{
name: "Pants",
description: "Winter",
},
{
name: "Casual",
description: "Winter",
price: 245,
},
{
name: "Shirt",
description: "Attire",
price: 150,
}
];
嗨,我正在尝试为没有使用函数的产品随机添加一个介于 0 到 100 之间的随机流行度分数。
我试图找出解决方案
https://levelup.gitconnected.com/set-data-structure-in-javascript-62e65908a0e6
和
https://medium.com/front-end-weekly/getting-a-random-item-from-an-array-43e7e18e8796
但仍然不确定如何在没有“流行”元素的情况下将元素添加到特定索引。谢谢!
解决方案
首先将数组过滤为您想要的元素,然后应用随机数
// function
const addRandomPopularityWhereThereIsNone = products => {
products.filter(p => !p.hasOwnProperty('popularity')).forEach(p => {
p.popularity = Math.floor(Math.random() * 101)
})
}
// call it
addRandomPopularityWhereThereIsNone(products)
请注意,这会修改原始数组。
以供参考:
推荐阅读
- angularjs - 如何在嵌套的 Firebase DB 中获取子节点
- video - 下载被拒绝的 vimeo/pixabay 视频
- python - pycharm python包已安装,但在导入包时抛出依赖错误(熊猫)
- c++ - 使用 UINT64_C 的目的?
- r - 在 R 中读取具有不同级别的许多变量的 json
- python - 如何忽略返回 Python 字典中的键值
- c# - c# 中的二进制到 .Beep 方法
- javascript - 如何测试提供上下文变量的 HOC 组件
- discord - discord.py 嵌入对象函数 add_field 参数 inline=True 不适用于移动设备?
- javascript - Alfresco 的高级定制