繁体   English   中英

在JavaScript中向数组内的特定对象添加对象属性时出现问题

[英]Problem in adding object properties to specific object inside array in JavaScript

我在JavaScript中有一个看起来像这样的对象

{
product_id: "2",
product_name: "Drinks"
}

对象的名称是product。

有一个数组包含上述对象的条目。 因此,每个数组项都是上述对象的一个​​条目。

在按钮上单击我检查数组中是否存在具有特定product_id(正在搜索)的对象条目。 如果数组中不存在具有特定product_id的对象,则必须将此新对象添加到数组中。 然而,如果具有特定product_id的对象条目存在,那么首先我向对象添加名为“qty”的新属性,然后将该对象作为新条目添加到该数组中。

下面是按钮点击的代码。

我在console.log()数组中查看结果。

当第一次单击该按钮时,我正确地获取数组条目,它显示数组中的对象。

第二次单击该按钮时,代码进入else条件,并将新属性(名称为qty)添加到对象中,然后将对象添加到数组中。 所以,现在数组有两个对象条目(第一个通过if条件添加,第二个通过else条件添加)。

奇怪的是,问题是当单击第二个时间按钮并执行else条件时,代码会修改先前的现有对象条目(已经存在于数组中)并在该对象条目中添加qty属性。

理想情况下,它应该将这两个条目视为单独的条目,如果我修改第二个对象条目,那么第一个条目(已经存在于数组中)应保持原样(这意味着没有qty属性),而它也会修改前一个条目并添加新的一个。

OnButtonClick() {
  if (array.length === 0) {
    array.splice(0, 0, product);
  }
  else {
    product.qty = 1;
    array.splice(0, 0, this.product);
  }
}

以下是完整代码:

// First Page: categories.ts sets the existing product object using a service 
// then navigates to the second page product.ts
ButtonClick() {
    this.Service.setProduct(product);
    this.route.navigate(['products']);
}

// Service page: service.ts

export class ManageService {
    products: any;
    ProductArray: any = [];

    constructor() { }
    public setProduct(data) {
      this.products = data;
    }

    public getProduct() {
        return this.products;
    }
}

//Second page: products.ts
// First it gathers the product object details that were passed from previous 
// categories.ts using getProduct() method in the service.ts 

export class ProductsPage implements OnInit {
    product: any = [];

    ngOnInit() {
        this.product = this.Service.getExtras();
    }

    ButtonClick(searchid: any) {
        // searchid is passed on button click
        let findsearchidarr = FindItem(searchid);
        if (findsearchidarr[0] === true) {
            this.Service.ProductArray[findsearchidarr[1]].quantity = 
++this.Service.ProductArray[findsearchidarr[1]].quantity;
            this.router.navigate(['categories']);
        }
        else if (findsearchidarr[0] === false) {
            this.product.quantity = 1;
            this.Service.ProductArray.splice(0, 0, this.product);
            this.router.navigate(['categories']);
        }
    }
FindItem (searchid: any) {
        let i = 0;
        let foundarray: any = [];

        for (let items of this.Service.ProductArray) {
        if (items.search_id.toLowerCase().includes(searchid)) {
            foundarray[0] = true;
            foundarray[1] = i;
            foundarray[2] = items.product_id;
            return foundarray;
        }
        i++;
        }
        foundarray[0] = false;
        foundarray[1] = -1;
        foundarray[2] = 0;
        return foundarray;
    }
}

请参阅下面的逻辑。 它将quantity属性添加到现有对象,否则向数组添加新对象。

products: any[] = [{
    product_id: "2",
    product_name: "Drinks"
  },
  {
    product_id: "3",
    product_name: "Wafers"
  },
  {
    product_id: "4",
    product_name: "Chocolates"
  }
];

productIDToSearch:number = 4;
quantityToAdd: number = 20;
let foundIndex = products.findIndex((val) => val.product_id == productIDToSearch);

if(this.foundIndex >= 0) {
    this.products[this.foundIndex].quantity = this.quantityToAdd;
}
else {
    this.products.push({product_id:productIDToSearch, product_name:'Ice-cream', quantityToAdd: 33});
    console.log(products);
}

等效的JavaScript代码

 var products = [{ product_id: "2", product_name: "Drinks" }, { product_id: "3", product_name: "Wafers" }, { product_id: "4", product_name: "Chocolates" } ]; let productIDToSearch = 5; let quantityToAdd = 20; let foundIndex = products.findIndex((val) => val.product_id == productIDToSearch); if(foundIndex >= 0) { products[foundIndex].quantity = quantityToAdd; console.log(products); } else { products.push({product_id:productIDToSearch, product_name:'Ice-cream', quantityToAdd: 33}); console.log(products); } 

问题是JavaScript对象是通过引用来处理的,所以当我尝试添加任何属性或修改对象数组中的任何属性时,它会产生混淆(至少在我的情况下)。

我找到的解决方案是首先将对象复制到另一个对象,以便排除“按引用”的可能性,然后使用新的“复制”对象来标记新条目。 这解决了这个问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM