简体   繁体   English

javascript object reduce中如何有条件地添加props?

[英]How to conditionally add props in javascript object reduce?

following functions reduces an array and maps a new object.以下函数减少一个数组并映射一个新的 object。

getProps() {
  return this.items
            .reduce((map,props)=>
              ({...map, [props.name]: props.value, checked: true)})
            }), {})
}

What I want to achieve is that I want to conditionally add the checked property(key) if a condition is satisfied.我想要实现的是,如果满足条件,我想有条件地添加选中的属性(键)。

something like this.像这样的东西。

 getProps() {
getProps() {
  return this.items
            .reduce((map, props)=>
              ( {...map
                , [props.name]: props.value
                , (props.required) ? checked: true : null
                
                  // which means that if props.required is true 
                  // then add checked: true 
                  // else do nothing (do not add checked)
  ,)})}), {})
}

EXP经验值

what this means is that if props.required is true then add the property checked with value true (so that key:value pair checked:true will be added else do nothing (means do not add the key:value pair checked:true) this意味着如果 props.required 为真,则添加检查值为真的属性(以便添加键:值对检查:真,否则什么也不做(意味着不添加键:值对检查:真)

UPDATE更新

It is not about conditionally assign 'true' value to the checked property.这不是有条件地将“真”值分配给选中的属性。
It is about to conditionally add checked property.即将有条件地添加选中的属性。 Note the difference here...注意这里的区别...

A simple if statement would do the trick:一个简单的if语句就可以解决问题:

getProps() {
  return this.items.reduce(
    (map, props) => {
      if (!props.checked) return map;
      return ({...map, [props.name]: props.value, checked: true });
    },
    {}
  );
}

or with the conditional operator:或使用条件运算符:

getProps() {
  return this.items.reduce(
    (map, props) => props.checked
      ? map
      : ({...map, [props.name]: props.value, checked: true }),
    {}
  );
}

I think you are after something like this我想你在追求这样的事情

{ [props.name]: props.value, ...(props.required && { checked: true }) }

And this is the equivalent using the ternary operator这是使用三元运算符的等价物

{ [props.name]: props.value, ...(props.required ? { checked: true } : {}) }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM