如何在一定条件下将对象添加到数组? [英] How can I add object to array by certain condition?
问题描述
我这样尝试:
<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>
我想添加条件.如果clubs数组中不存在newClub对象的id,那么我想将该对象添加到数组中
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
有效
但是我问.那是最好的方法吗?还是还有另一种更好的方法?
But I ask. Is that the best way? Or is there another better way?
推荐答案
有效
不,不是. :-)如果第一条目不匹配,则您正在推动新俱乐部:
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.
我在这里使用ES2015 +箭头功能,但是您可以使用ES5传统功能:
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);
}
循环位于some
中,如果回调曾经返回真实值,则返回true
,否则返回false
. (当回调函数返回真实值时,它也会提前停止.)
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);
}
这篇关于如何在一定条件下将对象添加到数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!