我只想检查对象键是否以特定的前缀开头。例如:
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...
}
答案 0 :(得分:1)
您可以获取密钥并对其进行测试。
var object = { 456:"Hello", 512:"Bye" },
key;
for (key in object) {
if (!key.startsWith('4')) continue;
console.log(key, object[key]);
}
答案 1 :(得分:0)
您可以使用Object.keys
将对象转换为以键为元素的数组,并对其进行迭代,您可以使用4
方法检查键是否以substr
开头
var obj = {
456: "Hello",
512: "Bye"
}
Object.keys(obj)
.forEach(e => e.substr(0, 1) == 4 ? console.log(e + ':' + obj[e]) : false)
答案 2 :(得分:0)
您可以简单地使用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)
})
答案 3 :(得分:0)
这有帮助吗?
var obj = {
456: "Hello",
512: "Bye"
}
Object.keys(obj).forEach(elem => {
if (elem.charAt(0) == 4) {
console.log(elem, obj[elem])
}
//else {}
});
答案 4 :(得分:0)
您可以使用索引来读取字符串,就像读取数组一样:
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] + "\"");
}
答案 5 :(得分:0)
Object.keys(total).filter(k => k.startsWith('your-specific-chars'))
答案 6 :(得分:-1)
var obj = {
456:"Hello",
512:"Bye",
444:"good morning"
}
Object.keys(obj).forEach(function(key){
if(key.startsWith('4'))
console.log(key, obj[key]);
})
您可以尝试一下。