0

I am creating an object which has few keys to it .

processData = memoize(
    ({
      data,
      group
    }:EnumValues): Array<ITypeData> => {
      return _.map(test, (test: ITest) => ({
        id: test.Id,
        name: test.Name,
        code: test.Code,
}))

Here I am creating the object. Here there is a key called code, so if I don't want to have this key if there is no group data available or that is not sent. as this processData function is getting called from two places where from one place it gets that group data and from another not getting.

I tried:

code : test && test.Code

but still it doesn't work. Is there another way to handle this?

1
  • Please keep in mind, if one of the answers works for you, please mark them as the answer to help other peeps in the community to find their solution easier if they facing the same issue. You can do this by using grey marks (tick) beside answers (you can only choose one), for more information please read this. Commented May 28, 2020 at 9:33

2 Answers 2

1

You can simply use a spread operator to achieve such a thing, so the output of your code should be something like this:

processData = memoize(
    ({
      data,
      group
    }:EnumValues): Array<ITypeData> => {
      return _.map(test, (test: ITest) => ({
        id: test.Id,
        name: test.Name,
        ...(test.Code && {code: test.Code})
}))

NOTE: The spread operator here is actually work as same as Object.assign(), so whenever the source be like null or undefined it won't apply it to the target.

Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

processData = memoize(
    ({
      data,
      group
    }:EnumValues): Array<ITypeData> => {
      return _.map(test, (test: ITest) => {
          return test ? {
            id: test.Id,
            name: test.Name,
            code: test.Code,
        } : {
              id: test.Id,
              name: test.Name,
          }
      })
    })

Comments

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.