如何以特定模式开头的js中访问对象的属性?

时间:2016-09-10 21:02:37

标签: javascript

如何以特定模式开头的js中访问对象的属性?

 Object object {
  s_id: 'sscdsdcksd',
  name: 'xyz',
  attachment_fdept: 'x.pdf',
  attachment_xdept: 'y.pdf'
 }

现在我想访问以附件开头的对象的所有属性。我怎样才能做到这一点?

2 个答案:

答案 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]);
    }
  }
}




希望这有帮助