0

Is there a way I can pass a parameter value into a function and use it as properties of an object?

const state = {
  name: 'xyz',
  properties: 'abc'
}
...
const handleStuff = (properties:string) => {
        const a = [...state.properties]
        if (action.status == true)
        {
            //some code
            return {
                ...state,
                properties: a
            }
        } else {
            //some code
            return {
                ...state,
                properties: a
            }
        }
    }
3
  • 2
    what is the typeof properties, is it an array? Commented Apr 21, 2021 at 15:38
  • 1
    I think you are looking for computed names: { [properties]: a }, but then properties must be (or convert to) a string, and it will be one property despite its name. Better provide an example input and expected result. Commented Apr 21, 2021 at 15:44
  • I want the 'properties' to be string, then some how I can process that value to the same as state properties. For example, If the parameter is 'name', I want to be able to access state properties by using 'state.name' .I have edited the code, hope it will clear up what I meant. Commented Apr 21, 2021 at 16:46

1 Answer 1

1

It is still not clear what result you are trying to reach, but generally you can access your properties by [] operator. if you want just to store state.name value into variable you should do following

const a = state[properties] // a will be 'xyz'

code below will be evaluated as spread operation performed on the string 'xyz'

const a = [...state[properties]] // a will be equal to ['x', 'y', 'z']

in your return statement, where you want to combine object and if you want to assign value to property with name properties (which is 'name' for example) you can

return {
  ...state,
  [properties]: a // name value from the state will be overridden with value of variable a
};
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! This is exactly what I'm looking for.

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.