徐州网站开发要多少钱,郑州seo排名收费,网页在线发短信平台,专业品牌建设服务口碑好需求#xff1a;
如果我有以下对象数组#xff1a;
[ { id: 1, username: fred }, { id: 2, username: bill }, { id: 2, username: ted } ]有没有办法循环遍历数组#xff0c;以检查特定的用户名值是否已经存在#xff0c;如果它什么都不做#xff0c;但是如果它没有用…需求
如果我有以下对象数组
[ { id: 1, username: fred }, { id: 2, username: bill }, { id: 2, username: ted } ]有没有办法循环遍历数组以检查特定的用户名值是否已经存在如果它什么都不做但是如果它没有用所述用户名(和新的ID)将新对象添加到数组
解决
方法 一
我假设id s在这里是独一无二的。 some是检查数组中事物存在的一个很好的函数
const arr [{ id: 1, username: fred }, { id: 2, username: bill }, { id: 3, username: ted }];function add(arr, name) {const { length } arr;const id length 1;const found arr.some(el el.username name);if (!found) arr.push({ id, username: name });return arr;
}console.log(add(arr, ted));方法二 这里我使用了带有.filter的ES6箭头功能来检查是否存在新添加的用户名。
var arr [{id: 1,username: fred
}, {id: 2,username: bill
}, {id: 3,username: ted
}];function add(name) {var id arr.length 1; if (arr.filter(item item.username name).length 0){arr.push({ id: id, username: name });}
}add(ted);
console.log(arr);