0

i have an array of json objects and i have a select input what i want to do it is when i choose something from that select input it adds it to that array and at the same time when i re select the same item it won't add it again but didn't find how to make it

this is my array initialized in the state :

      this.state = {    
        Modules_SubModules_Array: [{ "Module": "", "SubModules": [] }],  
    };

and this is the function that i use to make the insert to that array :

  Affect_Module_Submodule = (currentModuleTitle) => {
    if (this.state.Modules_SubModules_Array.some(item => item.Module == 
      currentModuleTitle)) {
        console.log("it includes")
    }

    else if (!this.state.Modules_SubModules_Array.some(item => item.Module 
   == currentModuleTitle)) {
        console.log("it doesnt include")
    }
}

the currentModuleTitle is the item that i picked from the select input i want to test if that array contains already that value it won't add it and if it's not it adds it iam stuck at it a while now if you can help me i could appreciate that

2
  • 1
    Pointless to run the same some() test twice Commented Aug 7, 2019 at 14:48
  • I assume that your actual problem is with nested modules, right? Your example should reflect that problem then, in other words: Ad an example that does not work Commented Aug 7, 2019 at 14:53

2 Answers 2

1

Affect_Module_Submodule = (currentModuleTitle) => {
  if (this.state.Modules_SubModules_Array.findIndex(item => item.Module ==
      currentModuleTitle) < 0) {
    this.state.Modules_SubModules_Array.push({
      "Module": currentModuleTitle,
      "SubModules": []
    })
  }
}

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

1 Comment

it worked i just replaced the push by splice so i can edit the first intial object
1

You could flatten the modules:

 const flatModules = modules => modules.flatMap(module => [module.Module, flatModules(module.Sub_Modules)]);

Then you can easily do:

flatModules(this.state.Modules_SubModules_Array).includes(currentModuleTitle)

5 Comments

u mean i just put the flatModules inside and if statement and that's it ?
@AOUADISlim the second part of the answer is what you should put in your if statement (.includes returns a boolean)
well it actually shows me an error Cannot read property 'flatMap' of undefined when i tried to test console.log(flatModules(this.state.Modules_SubModules_Array).includes(currentModuleTitle))
Thats because there are some obejcts in the tree were module.Sub_Modules is not set. Honestly you should change your datastructure to be consistent then
if u have a better idea i will be happy to try it

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.