Home > Software design >  How to get key from json in angular
How to get key from json in angular

Time:06-07

How to get key "employee "

{ employee":{"name":"John","age":12}

}

CodePudding user response:

It's not about Angular, this is plain Javascript:

const obj = { employee:{name:"John",age:12}}

const key = Object.keys(obj)[0]

CodePudding user response:

You can use forEach to get your output if you use Array Object

function example1(array){

    let res = [];
  array = [{"ex1":{"name":"John1","age":12}}, {"ex2":{"name":"John2","age":12}}, {"ex3":{"name":"John3","age":12}}]

    array.forEach((e, idx) => {
    res.push(Object.keys(e))
  })

  document.getElementById("ex1").innerHTML = JSON.stringify(res);
}
<input type="button" value="example1" onclick="example1()">  

<p id="ex1"></p>

if you just use only object you can use For...in to get your output

function example2(array){

    let res = [];
  obj = {"ex1":{"name":"John1","age":12}, "ex2":{"name":"John2","age":12}, "ex3":{"name":"John3","age":12}}

    for(var val in obj){
    res.push(val)
  }

  document.getElementById("ex2").innerHTML = JSON.stringify(res);
}
<input type="button" value="example2" onclick="example2()">  

<p id="ex2"></p>

But remember when you put object or array or whatever check its valid or not. In your object is invalid here is the correct format

{"employee":{"name":"John","age":12}}
  • Related