-1

i want to get the first element of a Object! the object looks like this:

const obj = {
   "val1": "test"
}

I already tried this:

obj[0]

but this is not working out for me :/

JSLNO
  • 5
  • 5
  • 1
    What do you mean *"first"* element? Objects' values are accessed by *name*, not position. – jonrsharpe May 03 '20 at 19:48
  • are you sure that is a "list" and you can reach it via obj[0] ? From my understanding, this is a definition of javascript objects which works in a way that is similiar to map. You need to read it via obj['val1'] or you need to convert it to an array or list structure to use it. – Hayra May 03 '20 at 19:49
  • Hey, i want to get the very first element of the object. I can't access is by the name, cause' the value of the string is unknown – JSLNO May 03 '20 at 19:49
  • But objects aren't semantically ordered data structures, why are you using them if order matters? Is there only one key? – jonrsharpe May 03 '20 at 20:04

3 Answers3

0

use Object.keys:

obj[Object.keys(obj)[0]]

crystalbit
  • 550
  • 2
  • 6
  • 18
0

You can get the value like obj['val1']. It's not an array. If you want to get in your style then you have to make it an array.

const values = Object.values(obj);
console.log(values[0]);

Demo:

const obj = {
   "val1": "test"
};
const values = Object.values(obj);
console.log(values[0]);
Sajeeb Ahamed
  • 3,723
  • 2
  • 14
  • 21
0

You can get the first key/value by,

const obj = {
    "val1": "test"
}

key = Object.keys(obj)[0];
value = obj[Object.keys(obj)[0]]

console.log(key, value)