There is a dynamic object with the item_description_
key suffix index.
In addition to these keys, there are other different keys.
const input = { ... item_description_1: "1" item_description_2: "2" item_description_3: "3" ... }
How can I get the counts of the item_description_
keys? Expected result should be 3 in the above example.
Advertisement
Answer
You can use Object.keys
to get all the keys of the object into the array; then filter on the key starting with item_description
and count the length of the resultant array:
const input = { another_key: 'x', item_description_1: "1", item_description_2: "2", item_description_3: "3", something_else: 4 } const cnt = Object.keys(input) .filter(v => v.startsWith('item_description')) .length; console.log(cnt);
If your browser doesn’t support startsWith
, you can always use a regex e.g.
.filter(v => v.match(/^item_description/))