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

underscore js : compare key object to array keys objects if exist remove existing add new

我尝试将 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,"name":"aymen" }];

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

谁能帮我开个脑洞;)

所以您要删除数组中具有 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>

我也试试

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

而且有效 ;)!