首页 > 解决方案 > 如何在对象数组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

但仍然不确定如何在没有“流行”元素的情况下将元素添加到特定索引。谢谢!

标签: javascriptarraysobjectrandomjavascript-objects

解决方案


首先将数组过滤为您想要的元素,然后应用随机数

// function
const addRandomPopularityWhereThereIsNone = products => {
  products.filter(p => !p.hasOwnProperty('popularity')).forEach(p => {
    p.popularity = Math.floor(Math.random() * 101)
  })
}

// call it
addRandomPopularityWhereThereIsNone(products)

请注意,这会修改原始数组。

以供参考:


推荐阅读