simple question here. How can I find a key in the state where the value is true? For instance. Lets say I have this set as state:
const [page, setPage] = useState({
1: false,
2: false,
3: false,
4: true,
5: false,
6: false,
7: false
});
How can I return the key where the value is true? in this case 4?
I would also like to return the length of the key / value pairs (7) and even be able to loop though the key / value pairs but that isn't as important as my main question.
Hope you can help. Thanks.
You can iterate through an object using
Object.keys(myObject) that will return all keys.Object.values(myObject) that will return all values.Object.entries(myObject) that will return all keys and values.Should look like this:
for (const [key, value] of Object.entries(page)) {
if (value) {
console.log(key);
}
}
You can use Object.entries() to get an array of [key, value] pairs, and then you can use all relevant array methods/properties:
const page = {
1: false,
2: false,
3: false,
4: true,
5: false,
6: false,
7: false
}
const entries = Object.entries(page)
console.log({ firstTrue: entries.find(([, v]) => v)?.[0] })
console.log({ numberOfKeys: entries.length })
However, it would be easier just to store the state as an array:
const page = [false, false, false, true, false, false, false]
console.log({ firstTrueIndex: page.findIndex(v => v) })
console.log({ numberOfItems: page.length })
Try this :
const [page, setPage] = useState({
1: false,
2: false,
3: false,
4: true,
5: false,
6: false,
7: false
});
let trueValue=[];
for (let i in page)
{
if (page[i] === true)
trueValue.push(i);
}
console.log(trueValue);
This code will iterate the object and gives the key when the value is true.