简体   繁体   中英

how to iterate a object array to get key and value in typescript

I have a object array and would like to get key and value by iterating though it, however I only get 0, 1 as index. anyone know why?

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
});

Object.keys gives the indices of the array itself, not the objects in the values. Iterate over the values and explore them:

 const variable = [{key1: "value1"}, {key2: "value2"}]; for (const value of variable) { const firstKey = Object.keys(value)[0]; console.log(firstKey); }

Please try like this.

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

it will output:

key1 value1
key2 value2

How about this: Loop through array:

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

The Object.keys method work on the Object not on the Arrays. If you want a loop through an Object, Then it will work fine like below,

 const keys = {key1: "value1", key2: "value2"}; Object.keys(keys).forEach((key) => { console.log(key); });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM