简体   繁体   English

使用Javascript编辑对象项

[英]Edit Object Item with Javascript

I am trying to edit data in an array based upon its id. 我正在尝试根据其ID编辑数组中的数据。 Here is my array: 这是我的数组:

var myCollection = {
"data": [
{ "id":"1", "Name":"John Smiths", "AMT_STD":"1.99"},
{ "id":"2", "Name":"Carlsberg", "AMT_STD":"1.99"},
{ "id":"3", "Name":"Samuel Adams", "AMT_STD":"1.99"}
  ]};

What I would like to be able to do is create a function that will allow me to find id=1 within the array and then update the value of AMT_STD to 1.00. 我希望能够做的是创建一个函数,允许我在数组中找到id = 1,然后将AMT_STD的值更新为1.00。

From looking at other questions I have managed to add to the array and delete items but I have not yet figured out how to find and then edit and item. 从查看其他问题我已设法添加到数组并删除项目,但我还没有想出如何查找,然后编辑和项目。

I use the code below to add items: 我使用下面的代码添加项目:

function Add_Item() {
myCollection.data.push( { "id":"4", "Name":"Fosters", "AMT_STD":"1.99" } );
}

I use the code below to delete items: 我使用下面的代码删除项目:

function findAndRemove(array, property, value) {
$.each(array, function(index, result) {
if(result[property] == value) {
array.splice(index, 1);
}    
});

called by findAndRemove(myCollection.data, 'id', '1'); 由findAndRemove调用(myCollection.data,'id','1');

I have tried to edit the findAndRemove function as that method can find the item within the array however I cant figure out the syntax to edit the item within the index and was hoping someone could point me in the right direction. 我试图编辑findAndRemove函数,因为该方法可以找到数组中的项目但是我无法弄清楚编辑索引中的项目的语法,并希望有人可以指出我正确的方向。

You can go that way, and have a function to do so.. 你可以这样做,并有一个功能这样做..

but if you can still change the format, consider having 但如果您仍然可以更改格式,请考虑使用

var myCollection = {
  data: {
    1:{Name:"John Smiths", "AMT_STD":"1.99"},
    2:{Name:"Carlsberg", "AMT_STD":"1.99"},
    3:{Name:"Samuel Adams", "AMT_STD":"1.99"}
  }
}

insertion or record updates could be done like this: 插入或记录更新可以这样做:

myCollection.data[4]={Name:"Fosters", "AMT_STD":"1.99" }

updating a value: 更新值:

myCollection.data[2]["AMT_STD"]="2.00"

retrieving data 检索数据

myCollection.data[1];//the full record
myCollection.data[1].Name;//just the name
myCollection.data[1]["AMT_STD"];//similar to the previous but can use more complex keys/names

delete a record 删除记录

delete myCollection.data[2];

this way no code to insert, search or delete is needed (using javascript object builtin habilities). 这样就不需要插入,搜索或删除代码(使用javascript对象内置的habilities)。 You can use strings as ids (not restricted to numbers) and you gain advantage of fast index search that javascript have 您可以使用字符串作为ID(不限于数字),并且您可以获得javascript具有的快速索引搜索功能

hope it helps. 希望能帮助到你。

There are good guidelines in the other answers. 其他答案中有很好的指导方针。 However, if you really want to do it similar to the findAndRemove function, the most analogous way would be the create a function findAndReplace as follows which takes as additional arguments the property to be updated upon finding a match ("AMT_STD" in your case) and the value it should be updated to (1.00 in your case): 但是,如果你真的想要这样做与findAndRemove函数类似,最类似的方法是创建一个函数findAndReplace,如下所示,它将查找匹配项时要更新的属性作为附加参数(在你的情况下为“AMT_STD”)它应该更新的值(在你的情况下为1.00):

   function findAndReplace(array, property, value, replaceProperty, replaceValue) {
    $.each(array, function(index, result) {
        if (result[property] == value) {
            result[replaceProperty] = replaceValue;
        }
    });
   } 

Call it as follows: 称其如下:

findAndReplace(myCollection.data, 'id', '1', 'AMT_STD', 1.00);

As an additional sidenote, the findAndRemove function you have in your question actually will cause javascript errors in some browsers. 作为补充说明,您在问题中使用的findAndRemove函数实际上会在某些浏览器中导致javascript错误。 You can't call the splice method in the middle of the ".each" function because jQuery will then try and run the function on one of the deleted objects in the array which then has an undefined value. 你不能在“.each”函数的中间调用splice方法,因为jQuery将尝试在数组中的一个已删除对象上运行该函数,然后该对象具有未定义的值。 The better way to do it is to save the index of the item to be deleted in a variable and then after .each has been executed run the splice function. 更好的方法是将要删除的项目的索引保存在变量中,然后在执行.each后运行splice函数。

How about this prototype method? 这个原型方法怎么样?

Array.prototype.updateById = function(id, key, val) {
  // Loop the array - this refers to the array in this context
  for (var i = 0; i < this.length; i++) {
    if (this[i].id == id) {
      this[i][key] = val;
      return true;
    }
  }
  return false;
};

// Use it like this:
var updateSuccess = myCollection.data.updateById(1, "AMT_STD", "1.00");

// updateSuccess is now a boolean indicating whether the object was found and updated

By prototyping it, you can use the method with any array object that contains objects with an id property. 通过原型设计,您可以将该方法用于包含具有id属性的对象的任何数组对象。

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

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