我怎样才能将变量用于对象名称(子对象的情况)

时间:2018-04-09 04:29:37

标签: javascript node.js

假设我有这样的数据

data = {
     personal : {
           sport : "Football"
     }
}

我尝试提取字符串。它的工作

let str1 = "personal"
let str2 = "sport"
console.log(data[str1][str2])

问题我有一个更多的字符串。每个字符串如此不同。我怎么能为每个字符串使用一个。

let str_1 = "personal.sport"
let str_2 = "personal.sport.xxx"
let str_3 = "personal.aaa.sport.xxx"
.....
..
let str_n = "bbb.ccc.ddd"


console.log(data[str_1])
console.log(data[str_2])
console.log(data[str_3])
....
... 
console.log(data[str_n])

谢谢。

3 个答案:

答案 0 :(得分:1)

我不完全确定我明白你的意思但这就是你所追求的目标吗?

var data = {
  personal: {
    sport: "Football"
  }
};

let str_1 = "personal.sport";
let str_2 = "personal.sport.xxx";
let str_3 = "personal.aaa.sport.xxx";

function getValue(path) {
  var obj = data;
  var props = path.split(".");
  
  for (const prop of props) {
    obj = obj[prop];
    
    if (!obj)
      return obj;
  }
  
  return obj;
}

console.log(getValue(str_1))

答案 1 :(得分:1)

试试这段代码:



let data = {
  personal: {
    sport: {
      xxx: "Football"
    },
    aaa: {
      sport: {
        xxx: "Football"
      }
    }
  }
};

let str_1 = "personal.sport";
let str_2 = "personal.sport.xxx";
let str_3 = "personal.aaa.sport.xxx";

function getVal(path, obj) {
  return path.split(/\./g).reduce((re, attr) => re[attr], obj);
}
console.log(getVal(str_1, data));
console.log(getVal(str_2, data));
console.log(getVal(str_3, data));




答案 2 :(得分:0)

选项1:通过键循环。



var data = {
  'foo': {
    'bar': 'xyz'
  },
  'one': {
    'two': 'three'
  },
  'error': 'Boom!'
};

var finder = function(data, findBy) {
  var keys = (findBy || '').split(/\./);
  var tmp = data;
  var key;
  while (keys.length) {
    key = keys.shift();
    if (tmp.hasOwnProperty(key)) {
      tmp = tmp[key];
      continue;
    }
    tmp = undefined;
    break;
  }
  return tmp;
};

console.log(finder(data, 'foo.bar'));
console.log(finder(data, 'error'));
console.log(finder(data, null));
console.log(finder(data, ''));




选项2:使用Function,许多开发者都不同意这一点,包含eval



var data = {
  'foo': {
    'bar': 'xyz'
  },
  'one': {
    'two': 'three'
  },
  'error': 'Boom!'
};

var finder = function(data, findBy) {
  var keys = '["' + (findBy || '').replace(/\./, '"]["') + '"]';
  var finderStr = 'return ' + JSON.stringify(data) + keys + ';';
  //console.log(finderStr);
  var func = new Function(finderStr);
  return func();
};

console.log(finder(data, 'foo.bar'));
console.log(finder(data, 'error'));
console.log(finder(data, null));
console.log(finder(data, ''));