Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
164
rated 0 times [  170] [ 6]  / answers: 1 / hits: 54156  / 9 Years ago, tue, december 29, 2015, 12:00:00

Sorry I don't know how to phrase the question title. Please help edit if possible.



I have an object like this:



{
a: 'jack',
b: {
c: 'sparrow',
d: {
e: 'hahaha'
}
}
}


I want to make it look like:



{
'a': 'jack',
'b.c': 'sparrow',
'b.d.e': 'hahaha'
}

// so that I can use it this way:
a['b.d.e']


jQuery is ok too. I know for the nested object, I can use a.b.d.e to get hahaha, but today I have to use it like a['b.d.e'] -_-!!!
How can I achieve this? Thanks in advance :)


More From » jquery

 Answers
38

You could use a recursive function to crawl the object and flatten it for you.




var test = {
a: 'jack',
b: {
c: 'sparrow',
d: {
e: 'hahaha'
}
}
};

function traverseAndFlatten(currentNode, target, flattenedKey) {
for (var key in currentNode) {
if (currentNode.hasOwnProperty(key)) {
var newKey;
if (flattenedKey === undefined) {
newKey = key;
} else {
newKey = flattenedKey + '.' + key;
}

var value = currentNode[key];
if (typeof value === object) {
traverseAndFlatten(value, target, newKey);
} else {
target[newKey] = value;
}
}
}
}

function flatten(obj) {
var flattenedObject = {};
traverseAndFlatten(obj, flattenedObject);
return flattenedObject;
}

var flattened = JSON.stringify(flatten(test));
console.log(flattened);




One way to reverse this, if needed, is a nested set of loops. There is probably a cleaner way to accomplish this though:




var test = {'a':'jack','b.c':'sparrow','b.d.e':'hahaha'};

function expand(target, keySeparator) {
var result = {};
for (var key in target) {
if (target.hasOwnProperty(key)) {
var nestedKeys = key.split(keySeparator);
// Get the last subKey
var leaf = nestedKeys[nestedKeys.length - 1];
// Get all subKeys except for the last
var branch = nestedKeys.slice(0, nestedKeys.length - 1);

var currentTarget = result;
for (var i = 0; i < branch.length; i += 1) {
var subKey = nestedKeys[i];
// If this is the first time visiting this branch, we need to instantiate it
if (currentTarget[subKey] === undefined) {
currentTarget[subKey] = {};
}
// Visit the branch
currentTarget = currentTarget[subKey];
}
currentTarget[leaf] = target[key];
}
}
return result;
}

var expanded = JSON.stringify(expand(test, .));
console.log(expanded);




[#63907] Sunday, December 27, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
daren

Total Points: 577
Total Questions: 114
Total Answers: 120

Location: Malaysia
Member since Fri, Dec 3, 2021
3 Years ago
;