JavaScript助手| startsWith()不是函数

JavaScript助手| startsWith()不是函数,javascript,ecmascript-6,Javascript,Ecmascript 6,我需要编写一个助手函数,该函数在对象数组中循环并过滤所有符合既定条件的名称。在我的例子中,所有以Zach 阵列示例: 我能够直接应用过滤器和映射检索所需结果,即: 我得到一个错误:I.startsWith不是一个函数 const filterZach=filteredNames(用户,“Zach”)//i.startsWith不是函数 const renderZach=filterZach.map(用户=>{ 返回`${user.firstName}${user.lastName}`; }

我需要编写一个助手函数,该函数在对象数组中循环并过滤所有符合既定条件的名称。在我的例子中,所有以
Zach

阵列示例:

我能够直接应用过滤器和映射检索所需结果,即:

我得到一个错误:I.startsWith不是一个函数

const filterZach=filteredNames(用户,“Zach”)//i.startsWith不是函数
const renderZach=filterZach.map(用户=>{
返回`${user.firstName}${user.lastName}

`; }).加入(“”);
问题:您能否帮助我理解出现此问题的原因,并向我展示使用帮助函数实现目标的替代方案

我没有嫁给
startsWith()
方法,我很想学习其他方法。也许减少


这是
filteredNames
内部的一个,带有
arr.filter(i
i
是一个对象,而不是字符串,对象没有
startsWith
方法。请改为引用对象的
firstName
,并在其上调用
startsWith

// helper
function filteredNames(arr, str) {
  return arr.filter(i => i.firstName.startsWith(str));
}
const用户=[
{
名字:“扎克”,
id:1,
姓:“沃尔斯克”
},
{
名字:“乖戾”,
id:2,
姓氏:“愤怒”
},
{
名字:“扎克”,
id:4,
姓:“T”
},
{
名字:“夏娃”,
id:5,
姓:“塞尔达”
},
{
名字:“扎卡里”,
id:6,
姓氏:“玩具”
}
];
//助手
函数过滤器名称(arr、str){
返回arr.filter(i=>i.firstName.startsWith(str));
}
const filterZach=filteredNames(用户,“Zach”)//i.startsWith不是函数
const renderZach=filterZach.map(用户=>{
返回`${user.firstName}${user.lastName}

`; }).加入(“”);
document.body.innerHTML+=renderZach;
谢谢@CertainPerformance,我唯一的问题是helper函数不知道
firstName
是什么。我的想法是让该helper存在并从一个单独的文件导入。请查看我添加的sandboxy。您可以将属性名传递给
startsWith
调用
>filteredNames
,如果你想的话,我猜?这取决于你想要编辑的逻辑类型,传递另一个参数并使用括号符号,然后我必须调用像
filteredNames(users,“Zach”,users.firstName)
?@NullisTrue否,
filteredNames(users,“Zach”,“firstName”)
const filterZach = users
  .filter(user => user.firstName.startsWith("Zach"))
  .map(user => {
    return `<p>${user.firstName} ${user.lastName}</p>`;
  }).join(""); // get rid of comas
// helper
function filteredNames(arr, str) {
  return arr.filter(i => i.startsWith(str));
}
const filterZach = filteredNames(users, "Zach") // i.startsWith is not a function
const renderZach = filterZach.map(user => {
    return `<p>${user.firstName} ${user.lastName}</p>`;
  }).join("");
// helper
function filteredNames(arr, str) {
  return arr.filter(i => i.firstName.startsWith(str));
}