我只想检查一个对象的键是否以特定前缀开头。例如:
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...
}
我只想检查一个对象的键是否以特定前缀开头。例如:
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...
}
Object.keys(total).filter(k => k.startsWith('your-specific-chars'))
您可以获取密钥并进行测试。
var object = { 456:"Hello", 512:"Bye" },
key;
for (key in object) {
if (!key.startsWith('4')) continue;
console.log(key, object[key]);
}
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)
你可以简单地使用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)
})
var obj = {
456: "Hello",
512: "Bye"
}
Object.keys(obj).forEach(elem => {
if (elem.charAt(0) == 4) {
console.log(elem, obj[elem])
}
//else {}
});
您可以使用索引读取字符串,就像读取数组一样:
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]);
})