Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript get key name from array of objects

from

"data":[{"ja":"大阪市"},{"en":"Osaka"}]

I want to get "ja" and "en".

I tried several ways...

data.map(function(_, i) { return i; });

it returns array of numbers.

console.log(Object.keys(Object.values(data)));

all trials return

(2) [0, 1]
0: 0
1: 1

what can I do ?? please answer me. thank you.

like image 733
horoyoi o Avatar asked Dec 02 '22 10:12

horoyoi o


1 Answers

Use map() and return the first key the object. You can get keys using Object.keys()

let data = [{"ja":"大阪市"},{"en":"Osaka"}]
let res = data.map(x => Object.keys(x)[0]);
console.log(res)

If you don't want to use [0] use flatMap()

let data = [{"ja":"大阪市"},{"en":"Osaka"}]
let res = data.flatMap(x => Object.keys(x));
console.log(res)

Note: The second method will also get the other properties other than first. For example

[{"ja":"大阪市","other":"value"},{"en":"Osaka"}] //["ja","other","en"];
like image 88
Maheer Ali Avatar answered Dec 23 '22 16:12

Maheer Ali