如何迭代对象数组以获取打字稿中的键和值

时间:2020-04-14 03:28:44

标签: javascript typescript typescript2.0

我有一个对象数组,想通过迭代来获取键和值,但是我只得到0、1作为索引。有人知道为什么吗?

const vairable = [{key1: "value1"}, {key2: "value2"}]
Object.keys(vairable).forEach((i: any) => {
    console.log(i); # get 0 and 1, I would like to have key1, key2
});

4 个答案:

答案 0 :(得分:4)

Object.keys给出数组本身的索引,而不是值中的对象。遍历值并探索它们:

const variable = [{key1: "value1"}, {key2: "value2"}];

for (const value of variable) {
    const firstKey = Object.keys(value)[0];
    console.log(firstKey);
}

答案 1 :(得分:1)

这如何:遍历数组:

const vairable = [{key1: "value1"}, {key2: "value2"}]
for(let e of vairable) {
  console.log(Object.keys(e))
}

答案 2 :(得分:1)

Object.keys方法对对象起作用,而不对数组起作用。如果您要遍历一个对象,则可以像下面这样正常工作

const keys = {key1: "value1", key2: "value2"};

Object.keys(keys).forEach((key) => {
  console.log(key);
});

答案 3 :(得分:1)

请尝试这样。

const vairable = [{key1: "value1"}, {key2: "value2"}]
vairable.forEach(item =>{
    for (const [key, value] of Object.entries(item)){
       console.log(key , value)
    }
})

它将输出:

key1 value1
key2 value2