如何以特定模式开头的js中访问对象的属性?
Object object {
s_id: 'sscdsdcksd',
name: 'xyz',
attachment_fdept: 'x.pdf',
attachment_xdept: 'y.pdf'
}
现在我想访问以附件开头的对象的所有属性。我怎样才能做到这一点?
答案 0 :(得分:2)
您可以使用Object.keys()
获取密钥,并使用.filter()
Object.keys(obj).filter( key => key.startsWith('attachment') )
var obj = {
s_id: 'sscdsdcksd',
name: 'xyz',
attachment_fdept: 'x.pdf',
attachment_xdept: 'y.pdf'
}
var keys = Object.keys(obj).filter( key => key.startsWith('attachment') )
console.log(keys);

如果您还需要值,而不仅仅是属性名称,那么:
Object.keys(obj).filter( key => key.startsWith('attachment') )
.map ( key => [key, obj[key]] );
var obj = {
s_id: 'sscdsdcksd',
name: 'xyz',
attachment_fdept: 'x.pdf',
attachment_xdept: 'y.pdf'
}
var pairs = Object.keys(obj).filter( key => key.startsWith('attachment') )
.map ( key => [key, obj[key]] );
console.log(pairs);

答案 1 :(得分:0)
var myObject = {
s_id: 'sscdsdcksd',
name: 'xyz',
attachment_fdept: 'x.pdf',
attachment_xdept: 'y.pdf'
};
for (var key in myObject) {
if (myObject.hasOwnProperty(key)) {
/*
Define your pattern here.
You can use regex for a more complicated pattern
*/
if (key.indexOf("attachment") === 0) {
console.log(key + " : " + myObject[key]);
}
}
}

希望这有帮助