How can I add object to array by certain condition

2019-09-22 08:18发布

问题:

I try like this :

<script type="text/javascript">
    var clubs = [ 
        {id: 1, name : 'chelsea'},
        {id: 2, name : 'city'},
        {id: 3, name : 'liverpool'}
    ];
    var newClub = {id: 4, name: 'manchester united'}
    for(var i=0; i<clubs.length; i++) {
        if(clubs[i].id!=newClub.id) {
            clubs.push(newClub);
            break;
        }
    }
    console.log(clubs);
</script>

I want to add condition. If id of newClub object is not exist in the clubs array, then I want to add the object to the array

It works

But I ask. Is that the best way? Or is there another better way?

回答1:

It works

No, it doesn't. :-) You're pushing the new club if the first entry isn't a match:

var clubs = [ 
    {id: 1, name : 'chelsea'},
    {id: 2, name : 'city'},
    {id: 3, name : 'liverpool'}
];
function pushClub(newClub) {
  for(var i=0; i<clubs.length; i++) {
      if(clubs[i].id!=newClub.id) {
          clubs.push(newClub);
          break;
      }
  }
}
var newClub = {id: 4, name: 'manchester united'}
pushClub(newClub);
pushClub(newClub);
console.log(JSON.stringify(clubs));
.as-console-wrapper {
  max-height: 100% !important;
}
Note that there are two id = 4 clubs.

You need to loop through the whole array before you know whether you should add the new item.

I'd probably use Array#some to see whether the item was present:

if (!clubs.some(c => c.id == newClub.id)) {
    clubs.push(newClub);
}

var clubs = [ 
    {id: 1, name : 'chelsea'},
    {id: 2, name : 'city'},
    {id: 3, name : 'liverpool'}
];
function pushClub(newClub) {
  if (!clubs.some(c => c.id == newClub.id)) {
    clubs.push(newClub);
  }
}
var newClub = {id: 4, name: 'manchester united'}
pushClub(newClub);
pushClub(newClub);
console.log(JSON.stringify(clubs));
.as-console-wrapper {
  max-height: 100% !important;
}
Note that there is only one id = 4 club.

I'm using an ES2015+ arrow function there, but you could use an ES5 traditional function:

if (!clubs.some(function(c) { return c.id == newClub.id; })) {
    clubs.push(newClub);
}

The loop is in some, which returns true if the callback ever returns a truthy value, or false if it never does. (It also stops early when the callback returns a truthy value.)


If you wanted to update the existing club if present, I'd use Array#find instead:

var existingClub = clubs.find(c => c.id == newClub.id);
if (existingClub) {
    existingClub.name = newClub.name;
} else {
    clubs.push(newClub);
}


回答2:

It does not work, because you insert in the first loop the object. You need to check all elements and if all element does not contain the wanted id, you could add the object top the array.

Not working code, spot the index.

var clubs = [{ id: 1, name: 'chelsea' }, { id: 2, name: 'city' }, { id: 3, name: 'liverpool' }],
    newClub = { id: 4, name: 'manchester united' },
    i;
    
for (i = 0; i < clubs.length; i++) {
  if (clubs[i].id != newClub.id) {
    clubs.push(newClub);
    break;
  }
}

console.log(i, clubs);

Working code with a check if all clubs do not contain the new id.

var clubs = [{ id: 1, name: 'chelsea' }, { id: 2, name: 'city' }, { id: 3, name: 'liverpool' }],
    newClub = { id: 4, name: 'manchester united' };
    
if (!clubs.some(({ id }) => id === newClub.id)) {
    clubs.push(newClub);
}

console.log(clubs);



回答3:

try with this

arr1.some function

var clubs = [{
    id: 1,
    name: 'chelsea'
  },
  {
    id: 2,
    name: 'city'
  },
  {
    id: 3,
    name: 'liverpool'
  }
];
var newClub = {
  id: 4,
  name: 'manchester united'
}
let found = clubs.some(r => r.id == newClub.id)
for (var i = 0; i < clubs.length; i++) {
  if (!clubs.some(r => r.id == newClub.id)) {
    clubs.push(newClub);
  }
}
console.log(clubs);