如何将数组字符串转换为属性?

时间:2019-04-22 07:02:35

标签: javascript arrays json object ecmascript-6

我需要按数组值调用JSON值,该怎么做?

var key = ['name','address'];

for(let i=0; i<key.length; i++){
   console.log(response.data.data.key[i]); // nothing happen
}

3 个答案:

答案 0 :(得分:1)

您正在寻找括号符号

var key = ['name','address'];

for(let i=0; i<key.length; i++){
   console.log(response.data.data[key[i]]); 
}

答案 1 :(得分:1)

使用动态属性符号:

var response = {
  data: {
    data: {
      name: "Jack",
      address: "Unknown"
    }
  }
};

var key = ['name', 'address'];

for (let i = 0; i < key.length; i++) {
  console.log(response.data.data[key[i]]);
}

答案 2 :(得分:0)

您可以使用forEach()来制作单个班轮代码:

var response = {
  data: {
    data: {
      'name': 'someName',
      'address': 'someAddress',
      'age': 10
    }
  }
}
var key = ['name','address'];

key.forEach((i) => console.log(response.data.data[i]));