如何基于对象内函数的用户输入访问对象属性?

时间:2019-05-09 15:22:06

标签: javascript

如何基于对象内函数的用户输入来访问对象属性? 我想称重为“马丁”作为参数,然后返回“马丁”的体重。 以这个为例:

const data = {
  info: [
    {name: "martin", weight: "2kg"},
  ],
  weight(name){
    return this.name[name].weight;
  },
};

console.log(data.weight("martin"));

4 个答案:

答案 0 :(得分:1)

基于OP的评论:

  

我希望能够访问数据的name属性。

为此,您将需要重组数据并使其成为对象。在这种情况下,您也不能使用相同的名称。下面是一个示例。

const data = {
  info: {
    martin:{weight: "2kg"},
    jack:{weight: "5kg"},
  },
  weight(name){
    return this.info[name].weight
  },
};

console.log(data.weight("martin"));
console.log(data.weight("jack"));

答案 1 :(得分:1)

如果要按名称访问它,则可以重组数据并按以下方式使用名称:

 const data = {
  info: {
    martin: { weight: "2kg"},
  },
  weight: function (name) {
    return this.info[name].weight || null;
  },
};

console.log(data.weight("martin"));

答案 2 :(得分:0)

如问题所述

  

我想用“马丁”作为参数调用体重,并返回“马丁”的体重

为此,您将需要使用http -v https://docker.elastic.co/v2/elasticsearch/elasticsearch/tags/list 'Authorization: Bearer some-long-token' HTTP/1.1 200 OK Connection: keep-alive Content-Length: 1765 Content-Type: application/json; charset=utf-8 Date: Thu, 09 May 2019 15:26:18 GMT Docker-Distribution-Api-Version: registry/2.0 X-Content-Type-Options: nosniff { "name": "elasticsearch/elasticsearch", "tags": [ "5.0.0-731e78df", "5.0.0-86a0b164", "5.0.0-alpha5", "5.0.0-beta1", "5.0.0-ccd69424", "5.0.0-rc1", "5.0.0", ... ... ... ,因为.find是一个数组。

如果找到它,则可以访问info

此行.weight很重要,因此不会出现错误return info ? info.weight : null;

Unable to access property weight of null or undefined

答案 3 :(得分:0)

如果要返回以“马丁”作为名称的每个对象的重量:

const data = {
  info: [
    {name: "martin", weight: "2kg"},
    {name: "alex", weight: "3kg"},
    {name: "martin", weight: "12kg"},
  ],
  getAll(name) {
    return this.info.filter(obj => obj.name == name);
  },
  weight(name){
    return this.getAll(name).map(obj => obj.weight);
  },
};

console.log(data.weight("martin"));