Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript grabbing object/json by index

I know how to grab array by its index. Also I know how to grab objects by its key, but I don't want to grab it by key.

Here you go for my objects

var x = {"email":["This Position"]}

And I know I can grab This Position like writing x.email[0].

But the problem is, I can't always grab the This Position with x.email[0].

Because the server sometimes sends me like this:

var x = {"phone":["This Position"]}

Even some time like this: var x = {"name":["This Position"]}

So you know to grab This Position not possible, because, for those variable, I have to write like x.phone[0] or x.name[0].

And it is very tough to write for hundred of variables.

 var x = {"email":["This Position"]}

So I want to grab This Position not with like this x.email[0].

Can give you me a solution that whatever key name, I just want to grab first first value first key? Is it possible?

like image 991
dudd Avatar asked Dec 31 '22 23:12

dudd


2 Answers

Use Object.values like so:

var x = {"email":["This Position"]};
const [[res]] = Object.values(x);
console.log(res);
like image 124
Jack Bashford Avatar answered Jan 08 '23 00:01

Jack Bashford


You can use Object.values

var x = {"email":["This Position"]}
var value = Object.values(x)[0][0]
like image 34
Anurag Srivastava Avatar answered Jan 08 '23 02:01

Anurag Srivastava