underline-js:将键对象与数组键对象进行比较,如果存在,则移除现有的添加新的

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

本文关键字:对象 添加 存在 数组 比较 如果 underline-js      更新时间:2023-09-26

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

   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"}];

i want 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);

它起作用;)!