Home > Software design >  How to find an object key using an variable?
How to find an object key using an variable?

Time:12-09

What I want is that my object listen to a string that I send to my function

for example :

const  [object,setobject] = useState([]);
      const HandleChange = (text,field) => {
        if (Object.keys(object).length > 0){ 
          var objects = values   ','   '{"'  field  '":'   text   '}'
        
          console.log(object[text])
          setobject(objects);
        }
        else {
          var objects = '{"'   field  '":'   '"'  text   '"}'
          setobject(objects);
          console.log(object[field]);
        } 
      }

from this object(which is a state) I want to get if there is any value equal to variable text inside my object, someone knows how can I find it ?

CodePudding user response:

It seems there several typos in your code (object or objects, console.log(object[text]) or console.log(object[field]), ...).

What I understand is that you wish to access object[field], but object is a String and not an Object.

Following this premise I would suggest converting it to an actual Object first, using JSON.parse(). Then you could check if object[field] already exists.

  • Related