简体   繁体   English

如何检查对象的键是否以特定字符开头?

[英]How to check if the keys of an object starts with a specific character?

I just want to check if an object key starts with a specific prefix or not.我只想检查对象键是否以特定前缀开头。 For example:例如:

var obj = {
  456: "Hello",
  512: "Bye"
}

//what I want to do with the object

if (obj.key starts with 4) {
  // do this....
} else {
  // do this...
}

You could get the key and test it.你可以拿到钥匙并测试它。

 var object = { 456:"Hello", 512:"Bye" }, key; for (key in object) { if (!key.startsWith('4')) continue; console.log(key, object[key]); }

Object.keys(total).filter(k => k.startsWith('your-specific-chars'))

You can use Object.keys to convert the object into an array with the keys as its elements and iterating it you can check if the key starts with 4 using substr method您可以使用Object.keys将对象转换为以键为元素的数组并对其进行迭代,您可以使用substr方法检查键是否以4开头

 var obj = { 456: "Hello", 512: "Bye" } Object.keys(obj) .forEach(e => e.substr(0, 1) == 4 ? console.log(e + ':' + obj[e]) : false)

You can simply use startsWith你可以简单地使用startsWith

 var obj = { 456:"Hello", 512:"Bye" } Object.keys(obj).forEach(e => { e.startsWith('4') ? console.log('start with 4 -->', e) : console.log('Do not start with 4 -->', e) })

Does this help?这有帮助吗?

 var obj = { 456: "Hello", 512: "Bye" } Object.keys(obj).forEach(elem => { if (elem.charAt(0) == 4) { console.log(elem, obj[elem]) } //else {} });

You can read a string using indices, just like you read an array:您可以使用索引读取字符串,就像读取数组一样:

 var object = { 456 : "Hello", 512 : "Bye" }; for (var key in object) { if (key[0] === "4") { console.log(key + " starts with 4"); } else { console.log(key + " does not start with 4"); } console.log("object[" + key + "] gives \\"" + object[key] + "\\""); }

 var obj = { 456:"Hello", 512:"Bye", 444:"good morning" } Object.keys(obj).forEach(function(key){ if(key.startsWith('4')) console.log(key, obj[key]); })

You can try this.你可以试试这个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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