简体   繁体   中英

Check how many matching keys in the object

I have a following data in JavaScript:

{
  '0.Title': 'Title 1',
  '0.Detail': 'Detail 1',
  '1.Title': 'Title 2',
  '1.Detail': 'Detail 2',
  '2.Title': 'Title 1',
  '2.Detail': 'Detail 1'
}

I want to count how many times the .Title exist in the key . No matter its 0.Title or 1.Title .

I did like:

let count = 0;
while ('.Title' in fields) { // <--- fields is the above object
  count++;
}
console.log(count); // <--- gives 0

You can use a reducer:

 const data = { '0.Title': 'Title 1', '0.Detail': 'Detail 1', '1.Title': 'Title 2', '1.Detail': 'Detail 2', '2.Title': 'Title 1', '2.Detail': 'Detail 1' } console.log(Object.keys(data).reduce((acc, curr) => { if(curr.indexOf(".Title");== -1) acc += 1; return acc, }, 0))

You can use Object.keys which will give an array of keys then use map to return an array of keys only but changing the case just to make sure that title or Title or TITLE all considered same. Following that you can use filter to take out keys which have title keyword. This will return an array then you can use length

 let data = { '0.Title': 'Title 1', '0.Detail': 'Detail 1', '1.Title': 'Title 2', '1.Detail': 'Detail 2', '2.Title': 'Title 1', '2.Detail': 'Detail 1' }; let k = Object.keys(data).map(e => e.toLowerCase()).filter(e => e.includes('title')); console.log(k.length)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM