1

I have this json array:

//val
0: {name: "jeg", class: "klase-jeg", id: "id-jeg"} 1: {age: 11, id: "jeg-id-11"} 2: {mail: "jeg mail", class: "jeg-klas-mail"}

and i want to get the first key of each json:

(name,age,mail)

This is my function:

$.map(val, Object.keys) //Result: ["name", "class", "id", "age", "id", "mail", "class"]

But the result is all the keys.

to get the first key from a json i used this:

obj = val[0]; Object.keys(obj)[0]); //Result: name

and i tried to use it with map but it didnt work :(

$.map(val, Object.keys[0]) //failed

i can use each or for, but i would like to know if can i use map with object.key to get the first key of each json.

Thanks!

Cristian Traìna
  • 7,056
  • 1
  • 31
  • 51
  • 1
    The "first" key of each object will vary from browser to browser - object keys are unordered - will this change your requirements? – tymeJV Jan 30 '19 at 17:11
  • Possible duplicate of [Sort JavaScript object by key](https://stackoverflow.com/questions/5467129/sort-javascript-object-by-key) – Cristian Traìna Jan 30 '19 at 17:14
  • 1
    You're better off just accessing the property you want rather than trying to get the "first" key when the first key may not actually be the key you want. – Kevin B Jan 30 '19 at 17:46
  • it doesnt metter the order because i just want to get the first key of each json whatever the order – Fernando Rangel Jan 30 '19 at 19:11

2 Answers2

0

I think you could do this :

assuming :

a = [{name: "jeg", class: "klase-jeg", id: "id-jeg"},{age: 11, id: "jeg-id-11"},{mail: "jeg mail", class: "jeg-klas-mail"}]

then do :

    a.map((el)=>{
    return Object.keys(el)[0];
    });

Hope it helps !

lagarto
  • 1
  • 1
  • 1
-1

You can use map and Object.keys like this:

const val = [
  {name: "jeg", class: "klase-jeg", id: "id-jeg"},
  {age: 11, id: "jeg-id-11"},
  {mail: "jeg mail", class: "jeg-klas-mail"}]

const firstKeys = val.map(a => Object.keys(a)[0]);
console.log(firstKeys)

/*
  In jquery:
  $.map(val, a => Object.keys(a)[0])
*/

$.map(val, Object.keys[0]) will throw an error because Object.keys is a function, not an array.

Update: Please note that properties' order in objects is not guaranteed in javaScript

adiga
  • 28,937
  • 7
  • 45
  • 66
  • i added a same answer an hour ago but deleted, because not sure about order of properties. because order is not guaranteed in object – Code Maniac Jan 30 '19 at 18:14
  • it doesnt metter the order because i just want to get the first key of each json whatever the order – Fernando Rangel Jan 30 '19 at 18:25
  • @CodeManiac I assumed OP wanted any first key decided by `Object.keys` (now confirmed). You're right, I should've probably mentioned that in the answer and now I'm stuck with -1 :( – adiga Jan 30 '19 at 18:31
  • @adiga I'm new asking here, can you tell me who did that -1 for your answer and what does it mean. (Is it permissible to ask this in a comment?) – Fernando Rangel Jan 30 '19 at 18:56