Home > Software design >  How to access an object's key using a state
How to access an object's key using a state

Time:10-14

I have an object and I want to access to key of the object using state.

This is the object:

cosnt data = {
    name: "this is title",
    description: "this is the description text"
}

This is the state:

const [filter, setFilter] = useState("description")

I can get the info using this line of code:

const pieceOfData = data.description // expected console.log = "this is the description text", so it works as expected!

I want to access using a state but I don't know what kind of a syntax I have to use:

const pieceOfData = data.filter
const pieceOfData = data.[filter]
const pieceOfData = data[filter]
const pieceOfData = data(filter)
//they are not giving the information

CodePudding user response:

You can use Bracket Notation to access an object's key using a state.

const [filter, setFilter] = useState("description");

const data = {
    name: "this is title",
    description: "this is the description text"
}

setFilter('description');

console.log(data[filter]);

CodePudding user response:

Hope it helps !

const data = {
    name: "this is title",
    description: "this is the description text"
}

console.log(data);

const filter = 'name';

console.log(data[filter]);

CodePudding user response:

Using data["key"]

const data = {
        name: "this is title",
        description: "this is the description text"
}

const [filter, setFilter] = useState("description")

const pieceOfData = data[filter]

console.log(pieceOfData);

CodePudding user response:

data[filter] should work also make sure proper syntax used for keyword. currently you defined object with wrong keyword.

CodePudding user response:

data[filter] should have worked but I am using Typescript. So @ManirajMurugan helped me to solve the problem.

This is the correct answer:

data[filter as keyof typeof data]
  • Related