1

i have a function like this:

const getKeysAs = (key1, key2) => {
    return {
        [key1]: state.key1,
        [key2]: state.key2
    }
}

So if state.key1 is 'a' and state.key2 is 'b', calling getKyesAs('one', 'two') would return

{
  one: 'a',
  two: 'b'
}

Now, if one of the argument is undefined, is there a way to not include it in the returned object ?

2
  • const o = {}; if (key1) o[key1] = ...;…? Commented Feb 17, 2021 at 13:07
  • 1
    Do you actually mean state[key1]? Commented Feb 17, 2021 at 14:14

4 Answers 4

1

You can Conditionally add properties to an Object with object destructuring

const obj = {
    ...(key1 && { [key1]: state[key1] }),
    ...(key2 && { [key2]: state[key2] })
};

If some of the args function is undefined, null or 0 (falsy values) then it will no be added to the object.

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

1 Comment

Object destructuring refers getting values out of an object. You are doing the opposite. This syntax is called object spread.
1

There is a very scalable way to do it:

const state= {
  a: "hello",

}
function getKeysAs (keys) {
return [...arguments].reduce((acc, cur)=> {
  const newValue = state[cur] && {[cur]: state[cur]}
  return {...acc, ...newValue}
}, {}) 
}

console.log(getKeysAs("a", "b"))

This way, you can pass as much keys as you need without worrying about scalability & undefined values.

4 Comments

Assuming the OP actually means to do state[key1], not state.key1 as in their example.
Yes indeed. I would suggest him to keep a consistent state then. It will make the code easier to understand and more scalable.
I agree if you mean that the state should be an array, not an object. But if you didn't mean that then state[key1] and state.key1 are both the same, right ? @DoneDeal0
In my example, the state is still an object. state[value] means state.nameOfMyDynamicValue and state.value means state.value. So by state[cur], you actually fetch state.nameOfCurrentKey. arguments is a native way to fetch all parameters from a function, it's not commonly used, so it looks fancy lol. Here arguments would be ["a", "b"]. so first reduce round => "a": state.a, then "b": state.b.
1

Use Object.assign().

const getKeysAs = (key1, key2) => {
    return Object.assign({}, key1 && {[key1]: state[key1]}, key2 && {[key2]: state[key2]});
}

Comments

0

Assuming you actually mean to do state[key1], not state.key1, here is a solution that doesn't create superfluous objects:

const getKeysAs = (...keys) => {
  const result = {};
  for (const key of keys) {
    if (key != null) {
      result[key] = state[key];
    }
  }
  return result;
}

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.