简体   繁体   English

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

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

I have an object in JavaScript that looks something like this 我在JavaScript中有一个看起来像这样的对象

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

The name of the object is product. 对象的名称是product。

There is an array that contains entries of the above object. 有一个数组包含上述对象的条目。 So, each array item is an entry of the above object. 因此,每个数组项都是上述对象的一个​​条目。

On button click I check if an object entry with a particular product_id (that is being searched) exists in the array or not. 在按钮上单击我检查数组中是否存在具有特定product_id(正在搜索)的对象条目。 If the object with the particular product_id does not exist in the array then I have to add this new object in to the array. 如果数组中不存在具有特定product_id的对象,则必须将此新对象添加到数组中。 Whereas if the object entry with the particular product_id exists then first I have add a new property named "qty" to the object and then this object is to be added as the new entry in to the array. 然而,如果具有特定product_id的对象条目存在,那么首先我向对象添加名为“qty”的新属性,然后将该对象作为新条目添加到该数组中。

Below is the code on button click. 下面是按钮点击的代码。

I console.log() the array to see the result. 我在console.log()数组中查看结果。

When the button is clicked the first time then I get the array entry correctly where it shows the object inside the array. 当第一次单击该按钮时,我正确地获取数组条目,它显示数组中的对象。

When the button is clicked the second time then the code goes in to the else condition and a new property (by the name qty) is added to the object and then the object is added in to the array. 第二次单击该按钮时,代码进入else条件,并将新属性(名称为qty)添加到对象中,然后将对象添加到数组中。 So, now the array has two object entries (first one is added through if condition and the second one is added through the else condition). 所以,现在数组有两个对象条目(第一个通过if条件添加,第二个通过else条件添加)。

Strangely, the problem is that when the second time button is clicked and the else condition is executed then the code modifies the previous existing object entry (which already is there in the array) and adds qty property in that object entry as well. 奇怪的是,问题是当单击第二个时间按钮并执行else条件时,代码会修改先前的现有对象条目(已经存在于数组中)并在该对象条目中添加qty属性。

Ideally it should treat these two as separate entries and if I modify the second object entry then the first entry (which already exists in the array) should remain as it is (which means without qty property) whereas it modifies the previous entry too and adds new one too. 理想情况下,它应该将这两个条目视为单独的条目,如果我修改第二个对象条目,那么第一个条目(已经存在于数组中)应保持原样(这意味着没有qty属性),而它也会修改前一个条目并添加新的一个。

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

Below is the full code: 以下是完整代码:

// 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;
    }
}

See the logic below. 请参阅下面的逻辑。 It adds the quantity property to already existing object otherwise adds a new object to array. 它将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);
}

Equivalent javascript code 等效的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); } 

The issue is that in JavaScript objects are treated by reference and so it creates confusion (at least in my case) when I try to add any property or modify any property inside the array of objects. 问题是JavaScript对象是通过引用来处理的,所以当我尝试添加任何属性或修改对象数组中的任何属性时,它会产生混淆(至少在我的情况下)。

The solution I found was to first copy the object to another object so that the "by reference" possibility is ruled out, then use the new "copied" object to mark a new entry. 我找到的解决方案是首先将对象复制到另一个对象,以便排除“按引用”的可能性,然后使用新的“复制”对象来标记新条目。 This solved the issue. 这解决了这个问题。

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

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