ES6将所有名称过滤到一个函数中

时间:2018-11-09 00:02:16

标签: javascript arrays ecmascript-6 refactoring

我正在尝试过滤对象数组并根据是否存在匹配项分配多个变量。

这样做的原因是,然后我可以在字符串文字中使用变量,以显示值。

我设法将其分解,但是我发现我在重复自己很多次,并认为这不是最有效的方法。

任何帮助将不胜感激。

let stats = [{name: "goals", value: 5},
{name: "losses", value: 20},
{name: "wins", value: 48},
{name: "draws", value: 23},
{name: "fwd_pass", value: 1533},
{name: "goal_assist", value: 2},
{name: "appearances", value: 80},
{name: "mins_played", value: 6953},
{name: "backward_pass", value: 308}]

//const { player , stats } = playerData[0]

const appearances = stats.filter(({name} , i) => {
      return name == "appearances"
});
const goals = stats.filter(({name} , i) => {
      return name == "goals"
});
const assists = stats.filter(({name} , i) => {
      return name == "goal_assist"
});
const mins = stats.filter(({name} , i) => {
      return name == "mins_played"
});
const fwdPass = stats.filter(({name} , i) => {
      return name == "fwd_pass"
});
const backPass = stats.filter(({name} , i) => {
      return name == "backward_pass"
});

3 个答案:

答案 0 :(得分:1)

您的方法将为每个变量返回数组。一种替代方法是创建一个以键为名称的对象。这样,您将可以使用名称进行访问并获取特定对象。

let stats = [{name: "goals", value: 5},{name: "losses", value: 20},{name: "wins", value: 48},{name: "draws", value: 23},{name: "fwd_pass", value: 1533},{name: "goal_assist", value: 2},{name: "appearances", value: 80},{name: "mins_played", value: 6953},{name: "backward_pass", value: 308}],
    variables = stats.reduce((a, c) => Object.assign(a, {[c.name]: c}), Object.create(null));

console.log(`Access through key: ${variables.fwd_pass.value}`);

答案 1 :(得分:1)

您可以创建一个函数,向其传递名称以过滤数据:

string

或者您可以创建对象映射并通过键进行访问:

let stats = [{ name: "goals", value: 5 }, { name: "losses", value: 20 }, { name: "wins", value: 48 }, { name: "draws", value: 23 }, { name: "fwd_pass", value: 1533 }, { name: "goal_assist", value: 2 }, { name: "appearances", value: 80 }, { name: "mins_played", value: 6953 }, { name: "backward_pass", value: 308 } ]

const fnFilter = (name) => stats.find(x => x.name == name)

console.log(fnFilter('appearances'))
console.log(fnFilter('backward_pass'))

答案 2 :(得分:0)

如果使用对象并将名称分配为属性,则代码将短很多。如果您想驼峰大小写变量或属性,它将总是更长。除非您使用正则表达式或字符串操作将名称值动态转换为camelCase。但这是不必要的拉伸

let stats = [{name: "goals", value: 5},
{name: "losses", value: 20},
{name: "wins", value: 48},
{name: "draws", value: 23},
{name: "fwd_pass", value: 1533},
{name: "goal_assist", value: 2},
{name: "appearances", value: 80},
{name: "mins_played", value: 6953},
{name: "backward_pass", value: 308}]

    //const { player , stats } = playerData[0]

const statsObj = {};
stats.forEach((item) => { statsObj[item.name] = item; } );

console.log(statsObj.wins); //outputs {name: "wins", value: 48}
console.log(statsObj.wins.value); //48