更新数组中的对象如何操作?

huangapple go评论89阅读模式
英文:

How to update object in array of objects?

问题

这是您要翻译的部分:

var cart = [];
var products = [
  {
    id: 1,
    productDescription: "Iphone 14 pro",
    price: 1544,
    quantity: 1
  },
  {
    id: 2,
    productDescription: "OPPOF19",
    price: 788,
    quantity: 1
  },
  {
    id: 3,
    productDescription: "Microsoft Surface Laptop 4",
    price: 2500,
    quantity: 1
  },
  {
    id: 4,
    productDescription: "Fog Scent Xpressio Perfume",
    price: 15,
    quantity: 1
  },
  {
    id: 5,
    productDescription: "Hyaluronic Acid Serum",
    price: 19,
    quantity: 1
  }
];

var item = products[Math.floor(Math.random() * products.length)];
if (localStorage.getItem('ItemsInCart')) {
  var previousCartItems = localStorage.getItem("ItemsInCart");
  cart = JSON.parse(previousCartItems);
  let obj = cart.some((o, i) => {
    if (o.id == item.id) {
      cart[i].quantity = cart[i].quantity + 1;
      localStorage.setItem("ItemsInCart", (JSON.stringify(cart)));
      return true;
    } else {
      item.quantity = 1;
      cart.push(item);
      localStorage.setItem("ItemsInCart", (JSON.stringify(cart)));
      return true;
    }
  });
} else {
  item.quantity = 1;
  cart.push(item);
  localStorage.setItem("ItemsInCart", (JSON.stringify(cart)));
}
console.log('*******************')
console.log(cart)
console.log('*******************')
英文:

I have a array of objects having products and I'm randomly choosing items from product object and adding to cart and then storing it into local storage. here whenever I'm trying to add the product already existing in the its creating duplicate object, instead of that I want to just increment and update the quantity attribute of the product.

here is my code what I'm trying to achieve.

var cart = [];
var products = [
{
id: 1,
productDescription: "Iphone 14 pro",
price: 1544,
quantity: 1
},
{
id: 2,
productDescription: "OPPOF19",
price: 788,
quantity: 1
},
{
id: 3,
productDescription: "Microsoft Surface Laptop 4",
price: 2500,
quantity: 1
},
{
id: 4,
productDescription: "Fog Scent Xpressio Perfume",
price: 15,
quantity: 1
},
{
id: 5,
productDescription: "Hyaluronic Acid Serum",
price: 19,
quantity: 1
}
];
var item = products[Math.floor(Math.random() * products.length)];
if (localStorage.getItem('ItemsInCart')) {
var previousCartItems = localStorage.getItem("ItemsInCart");
cart = JSON.parse(previousCartItems);
let obj = cart.some((o, i) => {
if (o.id == item.id) {
cart[i].quantity = cart[i].quantity + 1;
localStorage.setItem("ItemsInCart", (JSON.stringify(cart)));
return true;
} else {
item.quantity = 1;
cart.push(item);
localStorage.setItem("ItemsInCart", (JSON.stringify(cart)));
return true;
}
});
} else {
item.quantity = 1;
cart.push(item);
localStorage.setItem("ItemsInCart", (JSON.stringify(cart)));
}
console.log('*******************')
console.log(cart)
console.log('*******************')

答案1

得分: 1

"some" 在这里不太适合。 使用 "find" 更合适。 您查找,如果找到则增加数量,否则添加到购物车。

英文:

some is not best suited here. find is more appropriate for this. You find and if found increment else add to cart

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

var cart = [];
var products = [
{
id: 1,
productDescription: &quot;Iphone 14 pro&quot;,
price: 1544,
quantity: 1
},
{
id: 2,
productDescription: &quot;OPPOF19&quot;,
price: 788,
quantity: 1
},
{
id: 3,
productDescription: &quot;Microsoft Surface Laptop 4&quot;,
price: 2500,
quantity: 1
},
{
id: 4,
productDescription: &quot;Fog Scent Xpressio Perfume&quot;,
price: 15,
quantity: 1
},
{
id: 5,
productDescription: &quot;Hyaluronic Acid Serum&quot;,
price: 19,
quantity: 1
}
];
var item = products[Math.floor(Math.random() * products.length)];
if (localStorage.getItem(&#39;ItemsInCart&#39;)) {
var previousCartItems = localStorage.getItem(&quot;ItemsInCart&quot;);
cart = JSON.parse(previousCartItems);
const foundInCart = cart.find(e =&gt; e.id === item.id);
if (foundInCart) {
foundInCart.quantity += 1
localStorage.setItem(&quot;ItemsInCart&quot;, (JSON.stringify(cart)));
} else {
item.quantity = 1;
cart.push(item);
localStorage.setItem(&quot;ItemsInCart&quot;, (JSON.stringify(cart)));
}
} else {
item.quantity = 1;
cart.push(item);
localStorage.setItem(&quot;ItemsInCart&quot;, (JSON.stringify(cart)));
}
console.log(&#39;*******************&#39;)
console.log(cart)
console.log(&#39;*******************&#39;)

<!-- end snippet -->

jsfiddle

答案2

得分: 0

我不会为这个行为使用'some'。也许你想使用类似'map'的函数。这是我能想到的最简单的方法:

var item = products[Math.floor(Math.random() * products.length)]; 
if (localStorage.getItem('ItemsInCart')) {
    var previousCartItems = localStorage.getItem("ItemsInCart");
    cart = JSON.parse(previousCartItems);
    var position = cart.map(function(object) {return object.id; }).indexOf(item.id);
    var result = cart[position];
    if(!result){  
        item.quantity = 1;
        cart.push(item);
        localStorage.setItem("ItemsInCart", (JSON.stringify(cart)));
    }else{
        let index=cart.findIndex(x => x.id === result.id)   
        cart[index].quantity++;
        localStorage.setItem("ItemsInCart", (JSON.stringify(cart)));
    }
} else {
    item.quantity = 1;
    cart.push(item);
    localStorage.setItem("ItemsInCart", (JSON.stringify(cart)));
}
console.log('*******************')
console.log(cart)
console.log('*******************')
英文:

I wouldn't use 'some' for this behavior. Maybe you would like to use a function like 'map'. This is the simplest way I can think of:

var item = products[Math.floor(Math.random() * products.length)]; 
if (localStorage.getItem(&#39;ItemsInCart&#39;)) {
var previousCartItems = localStorage.getItem(&quot;ItemsInCart&quot;);
cart = JSON.parse(previousCartItems);
var position = cart.map(function(object) {return object.id; }).indexOf(item.id);
var result = cart[position];
if(!result){  
item.quantity = 1;
cart.push(item);
localStorage.setItem(&quot;ItemsInCart&quot;, (JSON.stringify(cart)));
}else{
let index=cart.findIndex(x =&gt; x.id === result.id)   
cart[index].quantity++;
localStorage.setItem(&quot;ItemsInCart&quot;, (JSON.stringify(cart)));
}
} else {
item.quantity = 1;
cart.push(item);
localStorage.setItem(&quot;ItemsInCart&quot;, (JSON.stringify(cart)));
}
console.log(&#39;*******************&#39;)
console.log(cart)
console.log(&#39;*******************&#39;)

答案3

得分: 0

I can provide the translated code part as requested:

如果您仍然想要使用某些数组方法来实现上述操作您可以通过以下方式来做尽管 map  find 方法是最适合的解决方案之一

var cart = [];
var products = [
  {
    id: 1,
    productDescription: "Iphone 14 pro",
    price: 1544,
    quantity: 1,
  },
  {
    id: 2,
    productDescription: "OPPOF19",
    price: 788,
    quantity: 1,
  },
  {
    id: 3,
    productDescription: "Microsoft Surface Laptop 4",
    price: 2500,
    quantity: 1,
  },
  {
    id: 4,
    productDescription: "Fog Scent Xpressio Perfume",
    price: 15,
    quantity: 1,
  },
  {
    id: 5,
    productDescription: "Hyaluronic Acid Serum",
    price: 19,
    quantity: 1,
  },
];

var item = products[Math.floor(Math.random() * products.length)];
console.log(item);
if (localStorage.getItem("ItemsInCart")) {
  var previousCartItems = localStorage.getItem("ItemsInCart");
  cart = JSON.parse(previousCartItems);
  let obj;
  let isAvailable = cart.some((o, i) => {
    if (o.id === item.id) {
      obj = o;
      return true;
    }
  });

  if (isAvailable) {
    obj.quantity = obj.quantity + 1;
    localStorage.setItem("ItemsInCart", JSON.stringify(cart));
  } else {
    item.quantity = 1;
    cart.push(item);
    localStorage.setItem("ItemsInCart", JSON.stringify(cart));
  }
} else {
  item.quantity = 1;
  cart.push(item);
  localStorage.setItem("ItemsInCart", JSON.stringify(cart));
}
console.log("*******************");
console.log(cart);
console.log("*******************");

You can copy and paste this translated code into your project as needed.

英文:

Hey in case you still want to use some array method to achieve the above you can do this by the below though map and find methods are best suited solutions

var cart = [];
var products = [
{
id: 1,
productDescription: &quot;Iphone 14 pro&quot;,
price: 1544,
quantity: 1,
},
{
id: 2,
productDescription: &quot;OPPOF19&quot;,
price: 788,
quantity: 1,
},
{
id: 3,
productDescription: &quot;Microsoft Surface Laptop 4&quot;,
price: 2500,
quantity: 1,
},
{
id: 4,
productDescription: &quot;Fog Scent Xpressio Perfume&quot;,
price: 15,
quantity: 1,
},
{
id: 5,
productDescription: &quot;Hyaluronic Acid Serum&quot;,
price: 19,
quantity: 1,
},
];
var item = products[Math.floor(Math.random() * products.length)];
console.log(item);
if (localStorage.getItem(&quot;ItemsInCart&quot;)) {
var previousCartItems = localStorage.getItem(&quot;ItemsInCart&quot;);
cart = JSON.parse(previousCartItems);
let obj;
let isAvailable = cart.some((o, i) =&gt; {
if (o.id === item.id) {
obj = o;
return true;
}
});
if (isAvailable) {
obj.quantity = obj.quantity + 1;
localStorage.setItem(&quot;ItemsInCart&quot;, JSON.stringify(cart));
} else {
item.quantity = 1;
cart.push(item);
localStorage.setItem(&quot;ItemsInCart&quot;, JSON.stringify(cart));
}
} else {
item.quantity = 1;
cart.push(item);
localStorage.setItem(&quot;ItemsInCart&quot;, JSON.stringify(cart));
}
console.log(&quot;*******************&quot;);
console.log(cart);
console.log(&quot;*******************&quot;);

jsfiddle

答案4

得分: 0

你过于复杂化了事情

const item = products[Math.floor(Math.random() * products.length)];

const cart = JSON.parse(localStorage.getItem("ItemsInCart")) || [];

const cartItem = cart.find(cartItem => cartItem.id === item.id);

if (cartItem) {
  cartItem.quantity += 1;
} else {
  // 仅为了谨慎起见,如果以后要更改此对象,请不要将原始对象放入购物车,而是将其副本放入购物车。
  cart.push({ ...item, quantity: 1 });
}

localStorage.setItem("ItemsInCart", JSON.stringify(cart));
英文:

You're overcomplicating things.

const item = products[Math.floor(Math.random() * products.length)];

const cart = JSON.parse(localStorage.getItem(&quot;ItemsInCart&quot;)) || [];

const cartItem = cart.find(cartItem =&gt; cartItem.id === item.id);

if (cartItem) {
  cartItem.quantity += 1;
} else {
  // just for good measure, if you&#39;re going to mutate this object later on, 
  // don&#39;t push the original but a copy to the cart.
  cart.push({ ...item, quantity: 1 });
}

localStorage.setItem(&quot;ItemsInCart&quot;, JSON.stringify(cart));

huangapple
  • 本文由 发表于 2023年4月11日 15:41:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/75983515.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定