I have below array of objects.
const array = [{
field1: "val1",
field2: "val2",
field3: {
field1: "val1",
field2: "val2"
}
},
{
field1: "val1",
field2: "val2",
field3: {
field1: "val1"
}
}]
I need to get below output
const output = [{
key: "field1",
subkeys: []
},
{
key: "field2",
subkeys: []
},
{
key: "field3",
subkeys: ["field1", "field2"]
}]
I can get the top level field using this
const keys = array.map(x => Object.keys(x)[0]);
But not able to access the inner ones.
Kindly help... Thanks!!!
For getting all of the keys of an Object you can use Object. keys() . Object. keys() takes an object as an argument and returns an array of all the keys.
A nested data structure is an array or object which refers to other arrays or objects, i.e. its values are arrays or objects. Such structures can be accessed by consecutively applying dot or bracket notation. Here is an example: const data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] };
keys() method and the length property are used to count the number of keys in an object. The Object. keys() method returns an array of a given object's own enumerable property names i.e. ["name", "age", "hobbies"] . The length property returns the length of the array.
You can use the keysOf function to get an Array of all the Keys from the Object. Note that this will return an Array of Keys and not an Array of Strings. In this example, we create an Object with two fields: one containing the type of the first item in the Array and the second one containing the actual Array.
In JavaScript, getting the keys and values that comprise an object is very easy. You can retrieve each object’s keys, values, or both combined into an array. The examples below use the following object: The Object.keys () method returns an array of strings containing all of the object’s keys, sorted by order of appearance:
keys () returns an Array Iterator object with the keys of an array. keys () does not change the original array. keys () is an ES6 feature (JavaScript 2015). It is supported in all modern browsers:
The keys () method returns an Array Iterator object with the keys of an array. keys () does not change the original array.
You can reduce an array of Object keys on the top level and then check if value for this key is object - retrieve its nested keys, otherwise just leave the empty array of subkeys
const array = [{
field1: "val1",
field2: "val2",
field3: {
field1: "val1",
field2: "val2"
}
},
{
field1: "val1",
field2: "val2",
field3: {
field1: "val1"
}
}]
const result = array.map(item => {
return Object.keys(item).reduce((acc, rec) => {
if(typeof item[rec] === 'object') {
return [...acc, {key: rec, subkeys: Object.keys(item[rec])}]
}
return [...acc, {key: rec, subkeys: []}]
}, [])
})
console.log(result)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With