下划线js:将关键对象与数组键对象进行比较(如果存在)删除现有的add new

时间:2015-04-03 10:36:54

标签: javascript arrays underscore.js

我尝试将obj id与数组对象id进行比较,从数组中移除对象id = 1并array.push(obj);

   var array =[{"id":1,"name":"amine"},{"id":2,"name":"aymen"}] ;
    var obj = {"id":1, "name":"youssef"};

 array.push(obj);                  
 var newArray = _.uniq(array , function(item, key, id) {
                            return item.name;
                        });

console.log(newArray) ;

newArray = [{" id":1," name":" amine"},{" id":2,& #34;姓名":" aymen"}];

我想要newArray = [{" id":2,"名称":" aymen"},{" id":1 ," name":" youssef"}];`

任何人都可以帮助我的大脑;)

2 个答案:

答案 0 :(得分:0)

因此,您要删除数组中包含id的任何条目,然后使用id添加新对象。看起来最简单的事情就是按顺序完成这两件事:

array = _.filter(array, function(entry) { return entry.id != obj.id; });
array.push(obj);

实例:

var array = [{"id": 1, "name": "amine"}, {"id": 2, "name": "aymen"}];
var obj = {
  "id": 1,
  "name": "youssef"
};

array = _.filter(array, function(entry) {
  return entry.id != obj.id;
});
array.push(obj);

snippet.log(JSON.stringify(array));
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js"></script>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

如果您不喜欢使用_.filter,可以使用_.find然后使用Array#splice

var index = _.find(array, function(entry) { return entry.id == obj.id; });
if (index !== undefined) {
    array.splice(index, 1);
}
array.push(obj);

实例:

var array = [{
  "id": 1,
  "name": "amine"
}, {
  "id": 2,
  "name": "aymen"
}];
var obj = {
  "id": 1,
  "name": "youssef"
};

var index = _.find(array, function(entry) {
  return entry.id == obj.id;
});
if (index !== undefined) {
  array.splice(index, 1);
}
array.push(obj);

snippet.log(JSON.stringify(array));
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js"></script>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

答案 1 :(得分:0)

我也尝试

array = _.without(array , _.findWhere(array , {id: obj.id}));
array.push(obj);

它有效;)!