Javascript JS/TS最聪明的方法是如何迭代对象数组并进行一些更改

Javascript JS/TS最聪明的方法是如何迭代对象数组并进行一些更改,javascript,function,typescript,Javascript,Function,Typescript,有没有最聪明的方法可以达到同样的效果 简介: routes = [ { name: 'vehicle', activated: true}, { name: 'userassignment', activated: true}, { name: 'relations', activated: true}, { name: 'journeys', activated: true}, { name: 'expenses', activated: true} ]) 任务-创建一个函数,该函数采用上

有没有最聪明的方法可以达到同样的效果

简介:

 routes = [
{ name: 'vehicle', activated: true},
{ name: 'userassignment', activated: true},
{ name: 'relations', activated: true},
{ name: 'journeys', activated: true},
{ name: 'expenses', activated: true}
])

任务-创建一个函数,该函数采用上述数组和:

  • 将所有成员属性“已激活”更改为false
  • 将一个特定的“选定”成员设置为true(基于其“名称”)
  • 如果“选择”为“行程”或“费用”,则将其设置为true,但也设置为“关系” 成员为true
  • 我按照下面的代码做了,但我的上级希望它更智能

    highlightActiveRoute(array: any[], chosen: string) {
    array.forEach(element => {
      element.activated = false;
      if (element.name === chosen) {
        element.activated = true;
        if (element.name === 'journeys' || element.name === 'expenses') {
          this.routes[2].activated = true;
        }
      } 
    });
    
    } }


    我不确定我是否能写得更聪明些,但也许你能:)非常感谢你给我的灵感。

    我做了一些小改进。。 首先,变量
    元素.activated
    只被覆盖一次,在当前代码中被覆盖两次。还降低了代码的深度,以使其更具可读性。我希望他能帮助你。祝你好运

    highlightActiveRoute(array: any[], chosen: string) {
        array.forEach(element => {
            element.activated = element.name === chosen; 
            if (element.activated 
                && (element.name === 'journeys' || element.name === 'expenses') ) {
                    this.routes[2].activated = true;
            } 
        });
    }
    
    仅使用ArrayIterators(ECMAScript 2015)。使用以下代码,您不必担心数组中的任何元素是否会改变其位置:

    highlightActiveRoute(array: any[], chosen: string) {
    array.forEach(element=>{element.activated=false});
    if(['journeys','expenses'].includes(chosen))
    {  
        array[array.findIndex(element=>{return element.name==='relations'})].activated = true;
        array[array.findIndex(element=>{return element.name==='expenses'})].activated = true;
        array[array.findIndex(element=>{return element.name==='journeys'})].activated = true;
    }
    else
    {
        array[array.findIndex(element=>{return element.name===chosen})].activated = true;
    }
    
    return array;
    }
    

    如果您的代码正在工作,但您只是想让它“更好”(一个主观的术语,如果曾经有过的话),那么这里并不是真正适合它的地方。我们在这里解决问题,或者有时回答有关如何解决问题的技术问题。你可以考虑你的问题是否更适合什么“更聪明”?就性能或可读性而言?我投票将这个问题作为离题题结束,因为它属于Hello Jorge,谢谢你的回答。。。这可能不是我想要的,但如何确定阵列中的位置非常酷,谢谢,我将使用它:)