js数组对象去重的问题

代码如下:

var result = [];
var hash = {};
var hash_ = {};
var fileLists = [{filename: "登记icon.png",url:a},{filename: "审核icon.png",url:b},,{filename: "反馈icon.png",url:c}];
var obj = {filename: "审核icon.png",url:d};
fileLists.push(obj);
for(var i = 0; i < fileLists.length; i++) {
        var elem = fileLists[i].filename;
        var elem_ = fileLists[i].url;
        if(!hash[elem]) {
            if(!hash_[elem_]) {
                result.push(fileLists[i]);
                hash_[elem_] = true;
            };
            hash[elem] = true;
        }
}

console.log(result )
//结果是:[{filename: "登记icon.png",url:a},{filename: "审核icon.png",url:b},,{filename: "审核icon.png",url:c}]

数组对象去重每次都是保留数组下标靠前的对象,我想把新增的对象覆盖原来的对象该怎么做?

阅读 3.1k
7 个回答

var fileLists = [
  {filename: "登记icon.png",url:'a'},
  {filename: "审核icon.png",url:'b'},
  {filename: "反馈icon.png",url:'c'}];
var obj = {filename: "审核icon.png",url:'d'};

fileLists.map(item=>{
  if(item.filename === obj.filename) {
    item = Object.assign({}, item, obj)
  }
  return item
})
console.log(fileLists)

在else里面找到需要替换的然后覆盖,或者从后往前遍历?

新手上路,请多包涵

楼上说得对,先把fileLists反转一下, 或者从后往前遍历试试?

var fileLists = [
  {filename: "登记icon.png",url:'a'},
  {filename: "审核icon.png",url:'b'},
  {filename: "反馈icon.png",url:'c'}];
var obj ={filename: "审核icon.png",url:'d'};

function update(record) {
  let index = 0;
  for(let rec of fileLists) {  
    if(rec.filename == record.filename) {  
      // Delete old record
      fileLists.splice(index, 1,record);
    }
    index++;
  }

  //fileLists.push(record);
}

update(obj);

<let fileLists = [

{filename: "登记icon.png",url:'a'},
{filename: "审核icon.png",url:'b'},
{filename: "反馈icon.png",url:'c'}];

let obj = {filename: "审核icon.png",url:'d'};

fileLists.map(item=>{

if(item.filename === obj.filename) {
  item = Object.assign(item, obj)
}
return item

});

console.log(fileLists); >

遍历时从后往前遍历

推荐问题
宣传栏