1

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
});
3
  • What is keySelectors? You have an array of non-uniform objects in vairable. If you want the keys and values of each object, first iterate vairable, then use Object.entries() to iterate the properties of each object Commented Apr 14, 2020 at 3:33
  • @Phil Surprisingly Object.entries is not available in typescript it seems Commented Apr 14, 2020 at 3:41
  • 1
    @Isaac depends on your language level config. See stackoverflow.com/questions/39741428/… Commented Apr 14, 2020 at 3:42

4 Answers 4

4

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

How about this: Loop through array:

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.