Home > Software engineering >  How i push an item to nested object?
How i push an item to nested object?

Time:10-23

I have an object defined like this. I want to access the role object and push a value into it. I couldn't do it with a map anyway. Any help?

Example: That exactly what i want. I want to map and find role and push some items. I filter the object if there is the same element i just change its value

interface IInitial {
    init: string;
    lang: string;
}

interface IInitialValues {
    role: IInitial[];
    addPrivs: string;
}

const [initialValues, setInitialValues] = useState<IInitialValues[]>([]);
initialValues.map((item) => item.role)
             .push({
                 init: "test",
                 lang: "TR",
             })

OR

initialValues
    .map((item: any) => item === name)
    .filter((item: any) => {
        if (item.lang === activeLang) {
            item.init = value;
        }
    });

CodePudding user response:

You use state so you have to return new collection, and not modify the initial collection

///Update the state

setInitialValues(prevValues =>{
  return prevValues.map(item => {
     ///rule to find the item to add roles to
     if (item.addPrivs === 'somethig') {
       ///return cloned object with one more role item
       return {...item, roles:[...item.role, { init: 'newInit',  lang: 'new lang' } ] } 
     } else {
      /// does not match the rule return unmodified item
       return item;
      
     } 
  } )

} ) 

CodePudding user response:

initialValues.map((item) => item.role)
             .push(...initialValues, {
                 init: "test",
                 lang: "TR",
             })
  • Related