How to get all key in JSON object (javascript) - javascript

{"document":
{"people":[
{"name":["Harry Potter"],"age":["18"],"gender":["Male"]},
{"name":["hermione granger"],"age":["18"],"gender":["Female"]},
]}
}
From this JSON example, I would like to get the keys such as name, age, gender for each people.
How to do this?

I use Object.keys which is built into JavaScript Object, it will return an array of keys from given object MDN Reference
var obj = {name: "Jeeva", age: "22", gender: "Male"}
console.log(Object.keys(obj))

Try this
var s = {name: "raul", age: "22", gender: "Male"}
var keys = [];
for(var k in s) keys.push(k);
Here keys array will return your keys ["name", "age", "gender"]

var input = {"document":
{"people":[
{"name":["Harry Potter"],"age":["18"],"gender":["Male"]},
{"name":["hermione granger"],"age":["18"],"gender":["Female"]},
]}
}
var keys = [];
for(var i = 0;i<input.document.people.length;i++)
{
Object.keys(input.document.people[i]).forEach(function(key){
if(keys.indexOf(key) == -1)
{
keys.push(key);
}
});
}
console.log(keys);

ES6 of the day here;
const json_getAllKeys = data => (
data.reduce((keys, obj) => (
keys.concat(Object.keys(obj).filter(key => (
keys.indexOf(key) === -1))
)
), [])
)
And yes it can be written in very long one line;
const json_getAllKeys = data => data.reduce((keys, obj) => keys.concat(Object.keys(obj).filter(key => keys.indexOf(key) === -1)), [])
EDIT: Returns all first order keys if the input is of type array of objects

var jsonData = { Name: "Ricardo Vasquez", age: "46", Email: "Rickysoft#gmail.com" };
for (x in jsonData) {
console.log(x +" => "+ jsonData[x]);
alert(x +" => "+ jsonData[x]);
}

This function should return an array of ALL the keys (i.e. the key names) in a JSON object including nested key/value pairs.
function get_all_json_keys(json_object, ret_array = []) {
for (json_key in json_object) {
if (typeof(json_object[json_key]) === 'object' && !Array.isArray(json_object[json_key])) {
ret_array.push(json_key);
get_all_json_keys(json_object[json_key], ret_array);
} else if (Array.isArray(json_object[json_key])) {
ret_array.push(json_key);
first_element = json_object[json_key][0];
if (typeof(first_element) === 'object') {
get_all_json_keys(first_element, ret_array);
}
} else {
ret_array.push(json_key);
}
}
return ret_array
}
Using this function on the OP's original object
const op_object =
{
"document":{
"people":[
{
"name":[
"Harry Potter"
],
"age":[
"18"
],
"gender":[
"Male"
]
},
{
"name":[
"hermione granger"
],
"age":[
"18"
],
"gender":[
"Female"
]
}
]
}
}
var all_keys = [];
function get_all_json_keys(json_object, ret_array = []) {
for (json_key in json_object) {
if (typeof(json_object[json_key]) === 'object' && !Array.isArray(json_object[json_key])) {
ret_array.push(json_key);
get_all_json_keys(json_object[json_key], ret_array);
} else if (Array.isArray(json_object[json_key])) {
ret_array.push(json_key);
first_element = json_object[json_key][0];
if (typeof(first_element) === 'object') {
get_all_json_keys(first_element, ret_array);
}
} else {
ret_array.push(json_key);
}
}
return ret_array
}
get_all_json_keys(op_object, all_keys);
console.log(all_keys);
should yield
[ 'document', 'people', 'name', 'age', 'gender' ]
Note: This will return a unique list of all key names.

We must "parse" our jsonObject
console.log('{"key0":"value0", "key1":"value1"}');
var jsonObject = JSON.parse('{"key0":"value0", "key1":"value1"}')
Object.keys(jsonObject).forEach(key => {
console.log(jsonObject[key]); //values
console.log(key); //keys
})

Related

Separating (n) keys from array of objects into a single array with keys names

I need to perform filter in the array of objects to get all the keys. Although, whenever there is a obj inside of that key, I would need to get the key name and concat with the key name from the obj, so for example:
const data = [ id: 5, name: "Something", obj: { lower: True, higher: False } ]
result = ["id", "name", "obj.lower", "obj.higher"]
I could manage to do the above code, but, if there is more objs inside the data, I would need to keep adding a if condition inside of my logic, I would like to know if there is any other way, so it doesn't matter how many objects I have inside the objects, It will concat always.
The code I used from the above mention:
const itemsArray = [
{ id: 1, item: "Item 001", obj: { name: 'Nilton001', message: "Free001", obj2: { test: "test001" } } },
{ id: 2, item: "Item 002", obj: { name: 'Nilton002', message: "Free002", obj2: { test: "test002" } } },
{ id: 3, item: "Item 003", obj: { name: 'Nilton003', message: "Free003", obj2: { test: "test003" } } },
];
const csvData = [
Object.keys(itemsArray[0]),
...itemsArray.map(item => Object.values(item))
].map(e => e.join(",")).join("\n")
// Separating keys
let keys = []
const allKeys = Object.entries(itemsArray[0]);
for (const data of allKeys) {
if (typeof data[1] === "object") {
const gettingObjKeys = Object.keys(data[1]);
const concatingKeys = gettingObjKeys.map((key) => data[0] + "." + key);
keys.push(concatingKeys);
} else {
keys.push(data[0])
}
}
//Flating
const flattingKeys = keys.reduce((acc, val: any) => acc.concat(val), []);
What I would like to achieve, lets suppose I have this array of object:
const data =
[
{ id: 10, obj: {name: "Name1", obj2: {name2: "Name2", test: "Test"}}}
...
]
Final result = ["id", "obj.name", "obj.obj2.name2", "obj.obj2.test"]
OBS: The first obj contains all the keys I need, no need to loop through other to get KEYS.
I would like to achieve, all the keys from the first object of the array, and if there is objects inside of objects, I would like to concat the obj names (obj.obj2key1)
You could map the key or the keys of the nested objects.
const
getKeys = object => Object
.entries(object)
.flatMap(([k, v]) => v && typeof v === 'object'
? getKeys(v).map(s => `${k}.${s}`)
: k
),
getValues = object => Object
.entries(object)
.flatMap(([k, v]) => v && typeof v === 'object'
? getValues(v)
: v
),
data = { id: 1, item: "Item 001", obj: { name: 'Nilton001', message: "Free001", obj2: { test: "test001" } } },
keys = getKeys(data),
values = getValues(data);
console.log(keys);
console.log(values);
.as-console-wrapper { max-height: 100% !important; top: 0; }
something like this
const itemsArray = [
{ id: 1, item: "Item 001", obj: { name: 'Nilton001', message: "Free001", obj2: { test: "test001" } } },
{ id: 2, item: "Item 002", obj: { name: 'Nilton002', message: "Free002", obj2: { test: "test002" } } },
{ id: 3, item: "Item 003", obj: { name: 'Nilton003', message: "Free003", obj2: { test: "test003" } } },
];
const item = itemsArray[0];
const getAllKeys = (obj, prefix=[]) => {
if(typeof obj !== 'object'){
return prefix.join('.')
}
return Object.entries(obj).flatMap(([k, v]) => getAllKeys(v, [...prefix, k]))
}
console.log(getAllKeys(item))
The OP solution can be simplified by accepting a prefix param (the parent key) and a results param (defaulted to [] and passed into the recursion) to do the flattening...
let obj = { key0: 'v0', key1: { innerKey0: 'innerV0', innerInner: { deeplyNested: 'v' } }, key2: { anotherInnerKey: 'innerV' } }
function recursiveKeys(prefix, obj, result=[]) {
let keys = Object.keys(obj);
keys.forEach(key => {
if (typeof obj[key] === 'object')
recursiveKeys(key, obj[key], result);
else
result.push(`${prefix}.${key}`)
});
return result;
}
console.log(recursiveKeys('', obj))
function getKeys(obj) {
return Object.keys((typeof obj === 'object' && obj) || {}).reduce((acc, key) => {
if (obj[key] && typeof obj[key] === 'object') {
const keys = getKeys(obj[key]);
keys.forEach((k) => acc.add(`${key}.${k}`));
} else {
acc.add(key);
}
return acc;
}, new Set());
}
// accumulate the keys in a set (the items of the array may
// have different shapes). All of the possible keys will be
// stored in a set
const s = itemsArray.reduce(
(acc, item) => new Set([...acc, ...getKeys(item)]),
new Set()
);
console.log('Keys => ', Array.from(s));
You can use recursion as follows. Since typeof([1,3,5]) is object, we also have to confirm that value is not an array, !Array.isArray(value):
const obj = { id: 10, obj: {name: "Name1", obj2: {name2: "Name2", test: "Test"}}};
const getKeys = (o,p) => Object.entries(o).flatMap(([key,value]) =>
typeof(value) === 'object' && !Array.isArray(value) ?
getKeys(value, (p?`${p}.`:"") + key) :
(p ? `${p}.`: "") + key
);
console.log( getKeys(obj) );

Convert an array to json object by javascript

I am stuck to solve this problem.
Convert an array below
var input = [
'animal/mammal/dog',
'animal/mammal/cat/tiger',
'animal/mammal/cat/lion',
'animal/mammal/elephant',
'animal/reptile',
'plant/sunflower'
]
to json Object
var expectedResult = {
"animal": {
"mammal": {
"dog": true,
"cat": {
"tiger": true,
"lion": true
},
"elephant": true
},
"reptile": true
},
"plant": {
"sunflower": true
}
}
Which data structure and algorithm can I apply for it?
Thanks
You need to first split each element to convert to array
using reverse reduce method you can convert them to object.
And your last step is merge this objects.
Lodash.js merge method is an one way to merge them.
var input = ['animal/mammal/dog','animal/mammal/cat/tiger','animal/mammal/cat/lion', 'animal/mammal/elephant','animal/reptile', 'plant/sunflower']
var finalbyLodash={}
input.forEach(x=>{
const keys = x.split("/");
const result = keys.reverse().reduce((res, key) => ({[key]: res}), true);
finalbyLodash = _.merge({}, finalbyLodash, result);
});
console.log(finalbyLodash);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script>
To make the process more understandable, break the problem down into pieces.
The first step is convert each string into something we can use, converting this:
"animal/mammal/dog"
into this:
[ "animal", "mammal", "dog" ]
That's an array of property names needed to build the final object.
Two functions will accomplish this for you, String.prototype.split() to split the string into an array, and Array.prototype.map() to transform each of the array elements:
let splitIntoNames = input.map(str => str.split('/'));
The intermediate result is this:
[
[ "animal", "mammal", "dog" ],
[ "animal", "mammal", "cat", "tiger" ],
[ "animal", "mammal", "cat", "lion" ],
[ "animal", "mammal", "elephant" ],
[ "animal", "reptile" ],
[ "plant", "sunflower" ]
]
Next step is to iterate over each array, using Array.prototype.forEach() to add properties to the object. You could add properties to the object with a for loop, but let's do that with a recursive function addName():
function addName(element, list, index) {
if (index >= list.length) {
return;
}
let name = list[index];
let isEndOfList = index === list.length - 1;
element[name] = element[name] || (isEndOfList ? true : {});
addName(element[name], list, index + 1);
}
let result = {};
splitIntoNames.forEach((list) => {
addName(result, list, 0);
});
The result:
result: {
"animal": {
"mammal": {
"dog": true,
"cat": {
"tiger": true,
"lion": true
},
"elephant": true
},
"reptile": true
},
"plant": {
"sunflower": true
}
}
const input = [
"animal/mammal/dog",
"animal/mammal/cat/tiger",
"animal/mammal/cat/lion",
"animal/mammal/elephant",
"animal/reptile",
"plant/sunflower",
];
let splitIntoNames = input.map((str) => str.split("/"));
console.log("splitIntoNames:", JSON.stringify(splitIntoNames, null, 2));
function addName(element, list, index) {
if (index >= list.length) {
return;
}
let name = list[index];
let isEndOfList = index === list.length - 1;
element[name] = element[name] || (isEndOfList ? true : {});
addName(element[name], list, index + 1);
}
let result = {};
splitIntoNames.forEach((list) => {
addName(result, list, 0);
});
console.log("result:", JSON.stringify(result, null, 2));
You can create a function that will slice every element from the array by "/" than you put the results into a variable and than just mount the Json. I mean something like that below:
window.onload = function() {
var expectedResult;
var input = [
'animal/mammal/dog',
'animal/mammal/cat/tiger',
'animal/mammal/cat/lion',
'animal/mammal/elephant',
'animal/reptile',
'plant/sunflower'
]
input.forEach(element => {
var data = element.split('/');
var dog = data[2] === 'dog' ? true : false
var tiger = data[2] === 'cat' && data[3] === 'tiger' ? true : false
var lion = data[2] === 'cat' && data[3] === 'lion' ? true : false
expectedResult = {
data[0]: {
data[1]: {
"dog": dog,
"cat": {
"tiger": tiger,
"lion": lion
}
}
}
}
})
}
Late to the party, here is my try. I'm implmenting recursive approach:
var input = ['animal/mammal/dog', 'animal/mammal/cat/tiger', 'animal/mammal/cat/lion', 'animal/mammal/elephant', 'animal/reptile', 'plant/sunflower'];
result = (buildObj = (array, Obj = {}) => {
array.forEach((val) => {
keys = val.split('/');
(nestedFn = (object) => {
outKey = keys.shift();
object[outKey] = object[outKey] || {};
if (keys.length == 0) object[outKey] = true;
if (keys.length > 0) nestedFn(object[outKey]);
})(Obj)
})
return Obj;
})(input);
console.log(result);
I try with array reduce, hope it help
let input = [
"animal/mammal/dog",
"animal/mammal/cat/tiger",
"animal/mammal/cat/lion",
"animal/elephant",
"animal/reptile",
"plant/sunflower",
];
let convertInput = (i = []) =>
i.reduce((prev, currItem = "") => {
let pointer = prev;
currItem.split("/").reduce((prevPre, currPre, preIdx, arrPre) => {
if (!pointer[currPre]) {
pointer[currPre] = preIdx === arrPre.length - 1 ? true : {};
}
pointer = pointer[currPre];
}, {});
return prev;
}, {});
console.log(JSON.stringify(convertInput(input), null, 4));

How to make json tree through group by json data?

Please take a look at my current json.
[
{"mode": "AR","fname": "ta","lname":"da","w_lng":"2.xx","w_lat":"1.xx"....},
{"mode": "AR","fname": "ta","lname":"da","w_lng":"3.xx","w_lat": "4.xx"....},
{"mode": "AR","fname": "ka","lname":"ja","w_lng":"6.xx","w_lat": "5.xx"....}
]
Now What I am looking for:
{
"mode": "AR",
"results": [
{
"fname": "ta",
"lname": "da",
"w_level": [
{ "w_lng": "2.xx",
"w_lat": "1.xx"
"anothelevel":[........]
},
{"w_lng": "3.xx",
"w_lat": "4.xx"
"anothelevel":[........]
}
]
}
{
"fname": "ka",
"lname": "ja",
"w_level": [
{
"w_lng": "x.xx",
"w_lat": "x.xx"
.....................
}
]
}
]
}
It is same as we do in SQL group by. suppose First group by world, then country, then city, then village etc. I was tried through group by. but the result is not my expected output. Please suggest me what should I do.
objMap = {};
for (let temp of obj) {
if (!objMap[temp.mode]) {
objMap[temp.mode] = { mode: temp.mode, results: [] }
}
let tempObj = { w_level: [], fname: temp.fname, lname: temp.lname };
let w_level = {};
for (let key of Object.keys(temp)) {
if (key !== "fname" && key !== 'lname' && key !== 'mode') {
w_level[key] = temp[key];
}
}
tempObj.w_level.push(w_level)
objMap[temp.mode].results.push(tempObj)
}
NOTE:get object by using Object.values(objMap);
Solution using reduce:
const inArr = [{"mode":"AR","fname":"Kiran","lname":"Dash","w_lng": "1.23", "w_lat": "2.23"},{"mode":"AR1","fname":"Suman","lname":"Dash","w_lng": "3.23", "w_lat": "4.23"},{"mode":"AR","fname":"Raman","lname":"Dash","w_lng": "5.23", "w_lat": "6.23"},{"mode":"AR","fname":"Milan","lname":"Dash","w_lng": "7.23", "w_lat": "8.23"},{"mode":"AR1","fname":"Naman","lname":"Dash","w_lng": "8.23", "w_lat": "9.23"},{"mode":"AR2","fname":"Phulan","lname":"Dash","w_lng": "10.23", "w_lat": "11.23"}]
console.log(
Object.values(inArr.reduce((item, currItem) => {
var { mode, fname, lname } = currItem;
if (!item[mode]) item[mode] = { mode, results: [] };
let w_level = {};
for (let key of Object.keys(currItem)) {
if (key !== "fname" && key !== 'lname' && key !== 'mode') {
w_level[key] = currItem[key];
}
}
item[mode].results.push({fname: fname, lname: lname, w_level: [w_level]});
return item;
}, {}))
);
Code walk through:
Loop over the input array, and group into an object indexed by mode.
Create an object with a result array if the mode doesn't exist yet, and push to that array.
Note: For the sake of simplicity, I have done it to one level. Please use the same approach to create multiple levels if you want.
------At last I found solution-----------
const reduceArrayByKeys = (inArr, keys, restKey) => {
const reduced = inArr.reduce((prev, cur) => {
const copied = { ...cur }
keys.forEach(key => delete copied[key])
const existing = prev.find(item => keys.every(key => item[key] === cur[key]))
if (existing) {
existing[restKey].push(copied)
} else {
const newItem = {}
keys.forEach(key => newItem[key] = cur[key])
newItem[restKey] = [copied]
prev.push(newItem)
}
return prev
}, [])
return reduced
}
const reduced = reduceArrayByKeys(inArr, ['mode'], 'results')
reduced.forEach(item => {
const results = item.results
item.results = reduceArrayByKeys(results, ['fname', 'lname'], 'w_level')
item.results.forEach(child => {
child.w_level = reduceArrayByKeys(child.w_level, ['w_lng', 'w_lat'],
'other')
})
})

Find duplicate value in array of objects and merge some duplicate key and value

I have two arrays of objects
array = [
{
"id_0":356,
"name":"India",
"key1":150
},
{
"id_0":356,
"name":"India",
"key2":200
},
{
"id_0":748,
"name":"Swaziland",
"key1":140
},
{
"id_0":748,
"name":"Swaziland",
"key2":180
}
]
I am trying to find the duplicate id_0 in array of objects and merge the duplicate object of key2 and value.
I want the result to be:
array = [
{
"id_0":356,
"name":"India",
"key1":150,
"key2":200
},
{
"id_0":748,
"name":"Swaziland",
"key1":140,
"key2":180
}
]
How to find the duplicate value and merge the duplicate key and value in array?
You can use Array.prototype.reduce() to reduce your array as you need.
Duplicate item can be merged using Object.assign().
var array = [
{ 'id_0': 356, 'name': 'India', 'key1': 150 },
{ 'id_0': 356, 'name': 'India', 'key2': 200 }
];
var result = array.reduce(function(prev, item) {
var newItem = prev.find(function(i) {
return i.id_0 === item.id_0;
});
if (newItem) {
Object.assign(newItem, item);
} else {
prev.push(item);
}
return prev;
}, []);
console.log(result);
Object.assign is part of ES6. If it does not work for you, just replace it with:
for (var attrname in item) {
newItem[attrname] = item[attrname];
};
Try this fiddle
var array = [
{
"id_0":356,
"name":"India",
"key1":150
},
{
"id_0":356,
"name":"India",
"key2":200
},
{
"id_0":356,
"name2":"china",
"key2":200
}
]
function mergeArray( arr )
{
var outputObj = {};
for ( var counter = 0; counter < arr.length; counter++ )
{
var obj = arr[ counter ];
for( var key in obj )
{
if ( !outputObj[ key ] )
{
outputObj[ key ] = obj[ key ];
}
}
}
return outputObj;
}
console.log( mergeArray( array ) );
Edited the fiddle to suit your 'UPDATED' requirement
var array = [
{
"id_0":356,
"name":"India",
"key1":150
},
{
"id_0":356,
"name":"India",
"key2":200
},
{
"id_0":400,
"name2":"china",
"key2":200
},
{
"id_0":400,
"name2":"china",
"key2":200
}
]
function mergeArray( arr )
{
var outputObj = {};
for ( var counter = 0; counter < arr.length; counter++ )
{
var obj = arr[ counter ];
for( var key in obj )
{
if ( !outputObj[ key ] )
{
outputObj[ key ] = obj[ key ];
}
}
}
return outputObj;
}
function collateArray( arr )
{
var outputObj = {};
var result = [];
for ( var counter = 0; counter < arr.length; counter++ )
{
var obj = arr[ counter ];
var id_0value = obj[ "id_0" ];
if ( !outputObj[ id_0value ] )
{
outputObj[ id_0value ] = [];
}
outputObj[ id_0value ].push( obj );
}
console.log( outputObj );
for ( var key in outputObj )
{
result.push( mergeArray( outputObj[ key ] ) );
}
return result;
}
console.log( collateArray( array ) );
Use an temp Object as a map that stores key => item can make the time complexity to O(n):
var arr = [
{
"id_0":356,
"name":"India",
"key1":150
},
{
"id_0":356,
"name":"India",
"key2":200
},
{
"id_0":748,
"name":"Swaziland",
"key1":140
},
{
"id_0":748,
"name":"Swaziland",
"key2":180
}
];
// items: the array to be merged to unique.
// attrName: the attribute's name that is for distinguish,
// isOverwrite:decides whether the value will be overwrite by later ones or not. Default to false.
function getUnique(items, attrName, isOverwrite) {
// Map to keep reference to objects by its id.
var store = {};
// The array for output result.
var result = [];
isOverwrite = !!isOverwrite;
items.forEach(function(item) {
var id = item[attrName];
var key;
// Try to fetch item by id from store.
var target = store[id];
// If target item exist in store, its dulplicated, we need to merge it.
if (typeof target !== 'undefined') {
// If it's presented, we need to merge it into existing one.
for (key in item) {
if (!item.hasOwnProperty(key)) {
continue;
}
// If isOverwrite is true, always use the newest value, otherwise,
// we only apply values that are not exist in target yet.
if (isOverwrite || typeof target[key] === 'undefined') {
target[key] = item[key];
}
}
} else {
// If its not in store yet, put it a clone into result, and to map for
// later reference.
var clone = {};
for (key in item) {
if (item.hasOwnProperty(key)) {
clone[key] = item[key];
}
}
store[id] = clone;
// Also put it into the result array.
result.push(clone);
}
});
return result;
}
console.log(getUnique(arr, 'id_0'));

Javascript reflection: Get nested objects path

In this stackoverflow thread, i learnt you can get a object path via a simple string.
Accessing nested JavaScript objects with string key
consider the following:
var person = { name: "somename", personal: { weight: "150", color: "dark" }};
var personWeight = deep_value(person,"personal.weight");
I an trying to construct an array of the object values who are not of type 'object' from my 'person' object.
Hence the array would look like:
[['name', []],['personal.weight', []],['personal.color', []]];
I want them to look in that form because i have further use for it down the road.
That's what I've tried:
var toIterate = { name: "somename", personal: { age: "19", color: "dark" } }
var myArray = [];
$.each(toIterate, recursive);
function recursive(key, value) {
if (key !== null) {
myArray.push([key, []]);
}
else {
$.each(value, recursive);
}
}
console.log(myArray);
Just use recursion to walk the object.
var person = {
name: "somename",
personal: {
weight: "150",
color: "dark",
foo: {
bar: 'bar',
baz: 'baz'
},
empty: {
}
}
};
// however you want to do this
var isobject = function(x){
return Object.prototype.toString.call(x) === '[object Object]';
};
var getkeys = function(obj, prefix){
var keys = Object.keys(obj);
prefix = prefix ? prefix + '.' : '';
return keys.reduce(function(result, key){
if(isobject(obj[key])){
result = result.concat(getkeys(obj[key], prefix + key));
}else{
result.push(prefix + key);
}
return result;
}, []);
};
var keys = getkeys(person);
document.body.innerHTML = '<pre>' + JSON.stringify(keys) + '</pre>';
Then use Array.prototype.map to massage the array of keys into your preferred format.
Note the behaviour with person.personal.empty.
This does seem like a strange way to store an object's keys. I wonder what your 'further use for it down the road' is.
This is what worked for me. Note that, a raw map is created first and then mapped to an join the items in the Array with ..
var toIterate = {
name: "somename",
personal: {
age: "19",
color: "dark"
}
};
console.log(getObjPath(toIterate).map(item => item.join('.')));
function isObject(x) {
return Object.prototype.toString.call(x) === '[object Object]';
};
function getObjPath(obj, pathArray, busArray) {
pathArray = pathArray ? pathArray : [];
if (isObject(obj)) {
for (key in obj) {
if (obj.hasOwnProperty(key)) {
if (isObject(obj[key])) {
busArray = busArray ? bussArray : [];
busArray.push(key);
getObjPath(obj[key], pathArray, busArray);
} else {
if (busArray) {
pathArray.push(busArray.concat([key]));
} else {
pathArray.push([key]);
}
}
}
}
}
return pathArray;
}
Good Luck...
I found the following solution on github.
https://github.com/mariocasciaro/object-path

Categories

Resources