简体   繁体   中英

can't assign object value to object JavaScript

I am trying to assing an object to another object with the same type.

So, I have this object 'Language'

export class Language {
  languageDescription: string;
  languageCode: string;
  isDefault: boolean;
}

And I declared two objects selectedLanguage and childSelectedLanguage with the Language type :

@State<LanguageSelectorStateModel>({
  name: 'languageSelector',
  defaults: {
    languages: [],
    selectedLanguage: null,
    childSelectedLanguage: null
  }
})*

After the selectedLanguage is populated( no more null),

  @Action(UpdateSelectedLanguage)
  @ImmutableContext()
  updateSelectedLanguage({ getState, patchState }: StateContext<LanguageSelectorStateModel>, { languageCode }: UpdateSelectedLanguage) {
    const state = getState();
    const selectedLanguage = state.languages.find(language => language.languageCode === languageCode);
    state.selectedLanguage = selectedLanguage;
    patchState(state);
  }

I tried to assign the same content of this value : to childSelectedLanguage.

childSelectedLanguage = selectedLanguage;

But childSlectedLanguage still null, despite that selectedLanguage is not.

I tried also

  @Action(InitializeChildrenSelectedLanguage)
  initializeChildrenSelectedLanguage(
    { getState, patchState }: StateContext<LanguageSelectorStateModel>,
    {  }: InitializeChildrenSelectedLanguage
  ) {
    const state = getState();
    Object.assign(state.childSelectedLanguage, state.selectedLanguage);
    patchState(state);
  }

But also i can't assign the object to the content.

First question: Why I cannot assign the object?

Second question: How can I resolve the problem?

To create an object from an other, you can maybe use that kind of function

/**
 * Update attributes of Class or object.
 *
 * @param origin - Original Object
 * @param newValues - New Values
 */
export function updateFields<T>(origin: T, newValues: Partial<T>): T {
  if (typeof origin !== 'object' || typeof newValues !== 'object') {
    throw new Error('Arguments must be kind of Classe or Object');
  }

  const keys = (Object.keys(newValues) as unknown) as Array<keyof T>;
  const result = origin; // Reassignment of Function Parameters is prohibited so we do a copy.

  keys.forEach(function affectValues(key) {
    result[key] = newValues[key] as never;
  });
  return result;
}

In your code you can do this

state.selectedLanguage = updateFields<YourType>(state.selectedLanguage, selectedLanguage);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM