Javascript 如何基于对象内函数的用户输入访问对象属性?
如何基于对象内函数的用户输入访问对象属性? 我想用“martin”作为参数调用weight并返回“martin”的weight。 以此为例:Javascript 如何基于对象内函数的用户输入访问对象属性?,javascript,Javascript,如何基于对象内函数的用户输入访问对象属性? 我想用“martin”作为参数调用weight并返回“martin”的weight。 以此为例: const data = { info: [ {name: "martin", weight: "2kg"}, ], weight(name){ return this.name[name].weight; }, }; console.log(data.weight("martin")); 如质询所说, 我想用“mart
const data = {
info: [
{name: "martin", weight: "2kg"},
],
weight(name){
return this.name[name].weight;
},
};
console.log(data.weight("martin"));
如质询所说, 我想用“martin”作为参数调用weight并返回“martin”的weight 为此,您需要使用
.find
,因为info
是一个数组
如果找到它,您可以访问.weight
这行<代码>返回信息?信息权重:空非常重要,因此您不会遇到错误无法访问null或未定义的属性权重
const数据={
信息:[
{姓名:“马丁”,体重:“2kg”},
],
重量(名称){
让info=this.info.find(x=>x.name==name)
退货信息?信息权重:空;
},
};
console.log(data.weight(“martin”))代码>如果要返回每个对象的重量,并将“martin”作为名称:
const数据={
信息:[
{姓名:“马丁”,体重:“2kg”},
{姓名:“亚历克斯”,体重:“3公斤”},
{姓名:“马丁”,体重:“12公斤”},
],
getAll(名称){
返回这个.info.filter(obj=>obj.name==name);
},
重量(名称){
返回这个.getAll(name).map(obj=>obj.weight);
},
};
console.log(data.weight(“martin”))代码>基于OP的评论:
我希望能够访问数据的name属性
为此,您需要重新构造数据并使其成为对象。在这种情况下,你不能有相同的名字。下面是一个例子
const数据={
信息:{
马丁:{体重:2公斤},
杰克:{体重:5公斤},
},
重量(名称){
返回此。信息[名称]。重量
},
};
console.log(data.weight(“martin”));
控制台.日志(数据.重量(“千斤顶”))代码>如果要按名称访问,可以按如下方式重新构造数据并使用名称:
const data = {
info: {
martin: { weight: "2kg"},
},
weight: function (name) {
return this.info[name].weight || null;
},
};
console.log(data.weight("martin"));
预期输出是什么。@MaheerAli谢谢,已修复!预期的输出是:2kgI希望代码能够处理更多对象我不想这样做。我希望能够访问数据的name属性。我没有投你的反对票。你的代码很好,我说不出为什么会投反对票。添加一些解释。@LukaMomcilovic数据及其数组没有name属性。如果你想以这种方式访问它,你需要重新构造它并使它成为对象。@LukaMomcilovic如果这不是你想要的,请编辑你的问题,因为这是实现你所说的唯一方法。