如何通过特定条件将对象添加到数组?

时间:2022-04-03 09:02:43

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

我想补充条件。如果在俱乐部数组中不存在newClub对象的id,那么我想将该对象添加到数组中

It works

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

但我问。这是最好的方式吗?还是有另一种更好的方法吗?

3 个解决方案

#1


6  

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:

我可能会使用Array#some来查看该项目是否存在:

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:

我在那里使用ES2015 +箭头功能,但你可以使用ES5传统功能:

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.)

循环在某些中,如果回调返回一个真值,则返回true,否则返回false。 (当回调返回真值时,它也会提前停止。)


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

如果你想更新现有的俱乐部,我会使用Array#find代替:

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

#2


1  

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.

它不起作用,因为您在第一个循环中插入了对象。您需要检查所有元素,如果所有元素都不包含所需的ID,则可以在数组顶部添加对象。

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.

检查所有俱乐部是否包含新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


1  

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

#1


6  

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:

我可能会使用Array#some来查看该项目是否存在:

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:

我在那里使用ES2015 +箭头功能,但你可以使用ES5传统功能:

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.)

循环在某些中,如果回调返回一个真值,则返回true,否则返回false。 (当回调返回真值时,它也会提前停止。)


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

如果你想更新现有的俱乐部,我会使用Array#find代替:

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

#2


1  

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.

它不起作用,因为您在第一个循环中插入了对象。您需要检查所有元素,如果所有元素都不包含所需的ID,则可以在数组顶部添加对象。

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.

检查所有俱乐部是否包含新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


1  

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