-1

Hello I was trying to get the array of the data which was written in JSON

For example this is my JSON object

{
    Data1 : {
        Data2 : "hello",
        Data3 : "hi"
    },
    Data4 : {
        Data5 : "this is Karan",
    }
}

I want the output as an array which contains [Data1, Data4]

Is there any way to do this Thank you

Karan Gandhi
  • 45
  • 13

2 Answers2

0

It's simple using Object.keys()

The Object.keys() method returns an array of a given object's own enumerable property names, in the same order as we get with a normal loop.

var json = {
    Data1 : {
        Data2 : "hello",
        Data3 : "hi"
    },
    Data4 : {
        Data5 : "this is Karan",
    }
}

var keys = Object.keys(json);
console.log(keys);
Mamun
  • 66,969
  • 9
  • 47
  • 59
-1

You can do it in two ways. Either use Object.keys or you can use for..in loop to iterate the object and return push the keys in an array

let data = {
  Data1: {
    Data2: "hello",
    Data3: "hi"
  },
  Data4: {
    Data5: "this is Karan",
  }
}

/**** OPTION -1 *****/

let getKeys = Object.keys(data);
console.log('Option-1 Result ', getKeys)

/**** OPTION -2 *****/

let keysArray = [];
for (let keys in data) {
  keysArray.push(keys)
};
console.log(keysArray)
brk
  • 48,835
  • 10
  • 56
  • 78