javascript更新或向数组添加值

我想给数组添加值。 但相同的值可能会更新。 例如我的数组是

[{"abc1":"123456"},{"abc2":"123456"}] 

再次join的时候是abc1。 它可能会更新。 例如在正常情况下

 [{"abc1":"123456"},{"abc2":"123456"},{"abc1":"123456"}] 

但我想要

 [{"abc2":"123456"},{"abc1":"123456"}] 

我的代码

 var categories = [], arrIndex = {}; addOrReplace({"abc1":"125"}); addOrReplace({"abc2":"126"}); addOrReplace({"abc1":"127"}); addOrReplace({"abc3":"129"}); function addOrReplace(object) { var index = arrIndex[object[0]]; console.log("index:"+object[0]); if(index === undefined) { index = categories.length; } arrIndex[object[1]] = index; categories[index] = object; } console.log(categories); 

它没有显示正确的答案。 表明

 [{"abc3":"129"}] 

我想要

 [{"abc2":"126"},{"abc1":"127"},{"abc3":"129"}] 

怎么可能? 请帮帮我?

如果find索引,则可以使用Array#findIndex和plice对象,然后将新对象推送到categories

 function addOrReplace(object) { var key = Object.keys(object)[0], index = categories.findIndex(o => key in o); if (index !== -1) { categories.splice(index, 1); } categories.push(object) } var categories = []; addOrReplace({ abc1: "125"}); console.log(categories); addOrReplace({ abc2: "126"}); console.log(categories); addOrReplace({ abc1: "127"}); console.log(categories); addOrReplace({ abc3: "129"}); console.log(categories); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 
  var categories = new Map(); addOrReplace({"abc1":"125"}); addOrReplace({"abc2":"126"}); addOrReplace({"abc1":"127"}); addOrReplace({"abc3":"129"}); function addOrReplace(object) { for (var name in object) categories[name] = object; } console.log(categories); 
 var categories = [], arrIndex = {}; addOrReplace({"abc1":"125"}); addOrReplace({"abc2":"126"}); addOrReplace({"abc1":"127"}); addOrReplace({"abc3":"129"}); function addOrReplace(object) { for(var c in categories){ if(Object.keys(categories[c])[0] == Object.keys(object)[0]){ categories.splice(c,1) } } categories.push(object) } console.log(categories); //[{"abc2":"126"},{"abc1":"127"},{"abc3":"129"}] 

我不知道你怎么会最终使用最终的数据,但如果你正在寻找唯一性,我想build议去object hash而不是数组。

原来 :

 { "abc1" : "123456", "abc2" : "123456" } 

如果您现在添加{ "abc1" : "some_other_value" }

 { "abc1" : "some_other_value", "abc2" : "123456" } 

你也可以使用if(objectHash('abc1'))来检查值是否已经存在。

它可以避免额外的遍历,如果已经存在,将会覆盖值。