如何获取对象的属性名称并在javascript中使用该属性名称

时间:2018-06-28 09:42:31

标签: javascript object

我有一个名为mapped_errors的对象,它返回一个动态对象。

有时它的值是:

{ _id:
   { location: 'body',
     param: '_id',
     value: 123,
     msg: '_id is required and must be a string' } }

,有时它的值是:

{ _name:
   { location: 'body',
     param: '_name',
     value: 123,
     msg: '_name is required and must be a string' } }

我想输出msg值,如下所示:

let obj_key = Object.keys(mapped_errors);
console.log(mapped_errors.{obj_key}.msg); // i know this is wrong

;-)

5 个答案:

答案 0 :(得分:1)

您的代码中唯一的错误是mapped_errors.{obj_key}.msg。使用变量获取键名时,应使用[]来访问对象的属性值,例如mapped_errors[obj_key]

var mapped_errors = { _id:
   { location: 'body',
     param: '_id',
     value: 123,
     msg: '_id is required and must be a string' } };

let obj_key = Object.keys(mapped_errors);
console.log(mapped_errors[obj_key].msg);

mapped_errors = { _name:
   { location: 'body',
     param: '_name',
     value: 123,
     msg: '_name is required and must be a string' } }
     
obj_key = Object.keys(mapped_errors);
console.log(mapped_errors[obj_key].msg);

答案 1 :(得分:0)

只需使用其键循环对象即可:

Object.keys(mapped_errors).forEach(key => {
  const value = mapped_errors[key];

  console.log(value.msg);
})

或者如果您不想循环,因为只有一个条目,请尝试:

const key = Object.keys(mapped_errors)[0];

console.log(mapped_errors[key].msg);

答案 2 :(得分:0)

您可以检查属性是否存在# CFINDER IMPLEMENTATION #!/usr/bin/env python from itertools import combinations import igraph import optparse parser = optparse.OptionParser(usage="%prog [options] infile") parser.add_option("-k", metavar="K", default=3, type=int, help="use a clique size of K") options, args = parser.parse_args() if not args: parser.error("Required input file as first argument") k = options.k g = igraph.load(args[0], format="ncol", directed=False) cls = map(set, g.maximal_cliques(min=k)) edgelist = [] for i, j in combinations(range(len(cls)), 2): if len(cls[i].intersection(cls[j])) >= k-1: edgelist.append((i, j)) cg = igraph.Graph(edgelist, directed=False) clusters = cg.clusters() for cluster in clusters: members = set() for i in cluster: members.update(cls[i]) print "\t".join(g.vs[members]["name"])

您也可以像这样访问第一个键: mapped_errors.hasOwnProperty('_name')

希望这会有所帮助

答案 3 :(得分:0)

let obj = { _id:
   { location: 'body',
     param: '_id',
     value: 123,
     msg: '_id is required and must be a string' } }

console.log(obj[Object.keys(obj)[0]].msg)

答案 4 :(得分:0)

您可以将Object.keys与下面的索引一起使用

mapped_errors = { _id:
   { location: 'body',
     param: '_id',
     value: 123,
     msg: '_id is required and must be a string' } };
     
console.log(mapped_errors[Object.keys(mapped_errors)[0]].msg);     
     
mapped_errors = { _name:
   { location: 'body',
     param: '_name',
     value: 123,
     msg: '_name is required and must be a string' } };

console.log(mapped_errors[Object.keys(mapped_errors)[0]].msg);

Object.keys返回键数组[0]将获得第一个键,而mapped_errors[Object.keys(mapped_errors)[0]].msg将返回味精内容。