1

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

1
  • 1
    What do you mean by “call it dynamically”? Read the value? Call a function? Is there only exactly one key? Have you tried the relevant Object and Array methods? Commented Aug 7, 2018 at 8:39

2 Answers 2

3

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.

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

Comments

1

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

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.