0

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.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
wangdev87
  • 8,611
  • 3
  • 8
  • 31
  • [There's no such thing as a "JSON Object"](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/) See also [What is the difference between JSON and Object Literal Notation?](https://stackoverflow.com/q/2904131) – VLAZ Dec 08 '20 at 07:18
  • are there keys with different prefixes than `item_description_` and you only want to count the ones with `item_description_` prefix? – illusion Dec 08 '20 at 07:18
  • that's correct, there are other keys, and i only want the count of `item_description` prefix key counts @illusion – wangdev87 Dec 08 '20 at 07:18

3 Answers3

4

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/))
Nick
  • 138,499
  • 22
  • 57
  • 95
2
const keyPrefixToCount = 'item_description_';

const count = Object.keys(input).reduce((count, key) => {
  if (key.startsWith(keyPrefixToCount)) {
    count++
  }
  return count;
}, 0)

console.log(count) // 3 for your input

You probably should remove the prefix into a variable.

Edit: as per VLAZ comment, startsWith would be more accurate

DSCH
  • 2,146
  • 1
  • 18
  • 29
  • @VLAZ true, thanks for spotting that. I guess startsWith or a regex would be better – DSCH Dec 08 '20 at 07:21
0

i think with regular expression will also be a good choice, just two more lines:

const input = {
  item_descrip3: "22",
  item_description_1: "1",
  item_description_2: "2",
  item_description_3: "3",
  test22: "4"
}
const regex = /^item_description_[1-9][0-9]*$/
let result = Object.keys(input).filter(item => regex.test(item))
Eason Yu
  • 319
  • 1
  • 5