簡體   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