简体   繁体   中英

How to conditionally add props in javascript object reduce?

following functions reduces an array and maps a new 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)

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:

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 } : {}) }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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