1

I'm creating and returning this object with properties that originates in a deeply nested object:

const mapStateToProps = (state) => ({
  firstName: state.currentUser.obj.firstName,
  lastName: state.currentUser.obj.lastName,
  email: state.currentUser.obj.email,
})

Another way of doing it is like this:

const mapStateToProps = (state) => {
  const {
    obj: {firstName, lastName, email},
  } = state.currentUser;

  return {
    firstName,
    lastName,
    email,
  };
}

I'm pretty happy with the first example, but it would be nice to finde a way to skip the repetition of state.currentUSer.obj for every line.

Is there any conciser way to accomplish the above than the given examples?

Input object:

const state = {
  currentUser: {
    isUpdatingAccount: false,
    isUpdatingFavouriteColor: false,
    obj: {
      firstName: null,
      lastName: null,
      email: null,
      favoriteColor: null,
      favoriteTeam: null,
    },
  },    
}
4
  • can you provide the input sample? Commented Jan 10, 2018 at 13:01
  • 1
    Use const {firstName, lastName, email} = state.currentUser.obj; Commented Jan 10, 2018 at 13:02
  • Are those three keys guaranteed to be the only ones that exist? Commented Jan 10, 2018 at 13:08
  • No, there could be more keys. See update in question. Commented Jan 10, 2018 at 13:09

1 Answer 1

4

You can use nested destructuring to get the properties you want:

const state = {
  currentUser: {
    isUpdatingAccount: false,
    isUpdatingFavouriteColor: false,
    obj: {
      firstName: null,
      lastName: null,
      email: null,
      favoriteColor: null,
      favoriteTeam: null,
    },
  },    
}

const mapStateToProps = ({ currentUser: { obj: { firstName, lastName, email }}}) => ({
  firstName,
  lastName,
  email
})

console.log(mapStateToProps(state))

You should also add defaults as fallback to prevent errors in case parts of the structure are missing:

const state = {
  currentUser: {
    isUpdatingAccount: false,
    isUpdatingFavouriteColor: false
    // I've removed obj as an example with default fallback
  },    
}

const mapStateToProps = ({ currentUser: { obj: { firstName, lastName, email } = {}} = {}}) => ({
  firstName,
  lastName,
  email
})

console.log(mapStateToProps(state))

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

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.