mtleppay
mtleppay

Reputation: 281

JS array key dynamic

I have an api data

current: {
  errors: {},
  items: {
     Economy: {}
  }
}

Object key "Economy" can be different, for instance "Advance"

and i call it like

let current = current.items.Economy 

or let current = current.items.Advance

How can i call it dynamically? P.S. My front don't know what key will be return

Upvotes: 1

Views: 59

Answers (2)

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

You can use Object.keys(current.items).

let current = {
  errors: {},
  items: {
     Economy: {age: 10}
  }
}

let keys = Object.keys(current.items);
let currentVal = current.items[keys[0]];
console.log(currentVal);

You can also use for loop:

let current = {
  errors: {},
  items: {
     Economy: {age: 10}
  }
}
for(var key in current.items){
  console.log(current.items[key]);
}

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370659

Use Object.entries to get every key and value pair in an object. If items only has one such key-value pair, then just select the first entry:

const obj = {
  current: {
    errors: {},
    items: {
      Foo: {data: 'foo data'}
    }
  }
};

const [key, val] = Object.entries(obj.current.items)[0];
console.log(key);
console.log(val);

If you don't actually care about the dynamic key name and just want the inner object, use Object.values instead.

Upvotes: 3

Related Questions