[英]Check how many matching keys in the object
I have a following data in JavaScript:我在 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
.我想计算
.Title
在key
中存在多少次。 No matter its 0.Title
or 1.Title
.无论是
0.Title
还是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.您可以使用
Object.keys
将给出一个键数组,然后使用map
只返回一个键数组,但更改大小写只是为了确保title
或Title
或TITLE
都被认为是相同的。 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.