1

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...

6
  • Your code looks somewhat correct, the only thing weird is that it's probably better to do checked: props.required ? true : false Commented Aug 22, 2020 at 14:29
  • No. It's not working. Commented Aug 22, 2020 at 14:30
  • I think you didn't get my point. Commented Aug 22, 2020 at 14:31
  • It is not to conditionally assign value to checked property. It is about to conditionally add checked property. Note the difference here... Commented Aug 22, 2020 at 14:31
  • Might be easier to slap a result.checked = this.items.some(props => props.required); on the end. Commented Aug 22, 2020 at 14:50

2 Answers 2

1

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 }),
    {}
  );
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

wow this is a cool syntax. Can you share similar tricks? a like or something...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.