如何动态访问键值对是JS / React

时间:2020-09-29 21:25:51

标签: javascript arrays reactjs object key-value

我有一个电子表格元素,其单元格值存储在这样的对象中:

localCells = {A1: {input: 'hi', value: 'world'}, A2: {input:'how', value:'you?'}}

很长很像这样

localCells = {A1: {…}, B1: {…}, C1: {…}, D1: {…}, A2: {…}, …}

我有一个存储当前选定单元格的数组,如下所示:

selected = ["A1", "B3"]

当我执行一个函数时,我想从上面的数组中获取每个单元格的值

我已经尝试过了:

         for (let i = 0; i < selected.length; i++) {
          console.log(localCells.selected[i])
        }

这是我的错误:

Uncaught TypeError: Cannot read property '0' of undefined

谢谢

3 个答案:

答案 0 :(得分:1)

您只能将变量用作对象键,并且使用[]表示法。所以应该是:

for (let cellId of selected) {
    console.log(localCells[cellId])
}

答案 1 :(得分:1)

您可以使用以下代码:

let localCells = {A1: {input: 'hi', value: 'world'}, A2: {input:'how', value:'you?'}};
let selected = ["A1", "B3"];
for (let i = 0; i < selected.length; i++) {
    if (localCells[selected[i]])
        console.log(localCells[selected[i]]);
}

答案 2 :(得分:1)

您正在混淆点和括号符号的工作方式。在执行localCells.selected[i]时,要使该行代码起作用,您的对象将是:

localCells = {
  selected: [0,1,2,3]
}

这并不是说localCells.a1

您不能在此处使用圆点符号,需要使用方括号。分解使其更具可读性

var key = selected[i]
var cell = localCells[key];
console.log(cell);

一行

var cell = localCells[selected[i]];

示例运行:

var localCells = {
  A1: {
    input: 'hi',
    value: 'world'
  },
  B3: {
    input: 'how',
    value: 'you?'
  }
}
var selected = ["A1", "B3"]

for (var i = 0; i < selected.length; i++) {
  var key = selected[i];
  var cell = localCells[key];
  console.log(cell);

  var cell2 = localCells[selected[i]];
  console.log(cell2);
}

//using forEach
selected.forEach(function(key) {
  console.log(localCells[key]);
});

const selectedObjects = selected.map(function(key) {
  return localCells[key];
});
console.log(selectedObjects);