gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 23:19:59 25 4
gpt4 key购买 nike

我有一个名为: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

;-)

最佳答案

代码中唯一的错误是 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);

关于javascript - 如何获取对象的属性名称并在javascript中使用该属性名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51079604/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com