将对象添加到多维数组

问题描述 投票:0回答:4

我目前有这个数组

const items = [  
     {name: "tablet", description: "12inch", price: 700, popularity: 99},   
     {name: "phone", description: "8inch", price: 900},  
     {name: "computer", description: "32inch", price: 3000, popularity: 50},  
     {name: "laptop", dimensions: "17inch", price: 1500},             

];

并且要为当前必须输入的项目添加1到100之间的随机受欢迎程度得分。

我当前的代码:

for (var n = 0; n < 3; ++n) {           
if ([6 == 'undefined']) {  
var randomNum = Math.floor(Math.random() * 100);  
    items.push(('popularity:'), (randomNum));   

gives me the array:

[

{
  description: "12inch",
  name: "tablet",
  popularity: 99,
  price: 700
}, 

{
  description: "8inch",
  name: "phone",
  price: 900
}, 

{
  description: "32inch",
  name: "computer",
  popularity: 50,
  price: 3000
}, 

{
  dimensions: "17inch",
  name: "laptop",
  price: 1500
}, "popularity:", 51, "popularity:", 38, "popularity:", 92]

当我console.log时,

所以我想知道如何遍历数组的维,行和列,以便数组显示为:

{name: "tablet", description: "12inch", price: 700, popularity: 99},   
{name: "phone", description: "8inch", price: 900, popularity: 51},   
{name: "computer", description: "32inch", price: 3000, popularity: 50},   
{name: "laptop", dimensions: "17inch", price: 1500, popularity: 32}, 

谢谢!

javascript arrays push
4个回答
0
投票

您可以遍历项目,如果不存在,请添加缺少的字段:

const items = [
    { name: 'tablet', description: '12inch', price: 700, popularity: 99 },
    { name: 'phone', description: '8inch', price: 900 },
    { name: 'computer', description: '32inch', price: 3000, popularity: 50 },
    { name: 'laptop', dimensions: '17inch', price: 1500 },
];

items.forEach(i => i.popularity = i.popularity || Math.ceil(Math.random() * 100));

console.log(items);

由于您要声明一个介于1到100之间的值,所以您可能想使用Math.ceil()而不是Math.floor()


0
投票

您可以使用map()

const items = [
    { name: 'tablet', description: '12inch', price: 700, popularity: 99 },
    { name: 'phone', description: '8inch', price: 900 },
    { name: 'computer', description: '32inch', price: 3000, popularity: 50 },
    { name: 'laptop', dimensions: '17inch', price: 1500 },
];

const result = items.map(item => (item.popularity ? item : { ...item, popularity: Math.floor(Math.random() * 100) }));

console.log(result);

0
投票

您的代码if ([6 == 'undefined'])-我不会说语法错误,而是完整的逻辑错误。之所以等于if ([false]),是因为两个常量不相同,最后因为它是一个非空数组而变成了if (true)

有更好的方法可以做到这一点,最好的是Array.map()函数:

Array.map()

0
投票

使用const items = [{ name: 'tablet', description: '12inch', price: 700, popularity: 99 }, { name: 'phone', description: '8inch', price: 900 }, { name: 'computer', description: '32inch', price: 3000, popularity: 50 }, { name: 'laptop', dimensions: '17inch', price: 1500 }, ]; const result = items.map(item => (item.popularity ? item : { ...item, popularity: Math.floor(Math.random() * 100) })); console.log(result);map

nullish coalescing operator (??)
© www.soinside.com 2019 - 2024. All rights reserved.