json 如何更新对象数组中的对象?

flseospp  于 2023-04-13  发布在  其他
关注(0)|答案(4)|浏览(155)

我有一个对象数组,其中包含产品,我从产品对象中随机选择项目并添加到购物车,然后将其存储到本地存储中。这里,每当我试图添加已经存在于其创建重复对象中的产品时,我只想增加并更新产品的数量属性。
这是我的代码,我正在努力实现。

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('*******************')
j91ykkif

j91ykkif1#

some不是最适合这里。find更适合这个。你找到,如果找到增量else添加到购物车

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);
  const foundInCart = cart.find(e => e.id === item.id);
  if (foundInCart) {
    foundInCart.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('*******************')

jsfiddle

pxyaymoc

pxyaymoc2#

我不会使用'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('*******************')
9w11ddsr

9w11ddsr3#

嘿,如果你仍然想使用一些数组方法来实现上面的功能,你可以通过下面的方法来实现,尽管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("*******************");

jsfiddle

up9lanfz

up9lanfz4#

你把事情弄得太复杂了。

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 {
  // just for good measure, if you're going to mutate this object later on, 
  // don't push the original but a copy to the cart.
  cart.push({ ...item, quantity: 1 });
}

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

相关问题