Skip to content

Instantly share code, notes, and snippets.

@oleg-am
Created January 19, 2017 10:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oleg-am/ffcf0108acc91f7f1cbfadb54442b78b to your computer and use it in GitHub Desktop.
Save oleg-am/ffcf0108acc91f7f1cbfadb54442b78b to your computer and use it in GitHub Desktop.
const setValue = (state, key, value, obj = false) => {
if (Array.isArray(key) && key.length > 1) {
const keys = [...key];
const currentKey = keys.shift();
return {
[currentKey]: {
...state[currentKey],
...setValue(state[currentKey], keys, value, true),
},
};
}
if (obj) {
return {
[key[0]]: value,
};
}
return {
[key]: value,
};
};
// use:
// const actionCreator = (key, value) => ({
// type: types.SET_VALUE,
// key,
// value,
// });
// const initialState = {
// key1: {
// key2: {
// keyN: 'value'
// }
// }
// }
// const reducer = (state = initialState, action) => {
// switch (action.type) {
// case types.SET_VALUE:
// return {
// ...state,
// ...setValue(state, action.key, action.value),
// };
// default:
// return state;
// }
// };
// const key = ['key1', 'key2', 'keyN']
// const value = 'next value'
// actionCreator(key, value)
// result:
// reducer = {
// key1: {
// key2: {
// keyN: 'next value'
// }
// }
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment