JSFiddle - React, Tailwind, and code Playground
HTML
<script src='https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js'>
JavaScript
var isObject = function (obj) {
return Object.prototype.toString.call(obj) === "[object Object]";
};
var map = new Map();
var paths = [];
function three (tr) {
function findPath(branch, path) {
path = path.concat();
if (path.length && map.has(branch)) {
paths.push([path.concat(), map.get(branch).concat()]);
} else {
map.set(branch, path.concat());
Object.keys(branch).forEach(function (key) {
var val = branch[key];
if (Array.isArray(val) || isObject(val)) {
findPath(val, path.concat([key]));
} else {
paths.push([path.concat([key]), val]);
}
});
}
}
findPath(tr, []);
return paths;
}
var obj = {a:"A", b:{c:"C"}, d:[1,2,3,4,5]};
obj.obj = obj;
var msg = JSON.stringify(three(obj));
var obj2 = {};
JSON.parse(msg).forEach(function ([path, val]) {
if (Array.isArray(val)) {
if (val.length === 0) {
_.set(obj2, path, obj2);
} else {
_.set(obj2, path, _.get(obj2, val));
}
} else {
_.set(obj2, path, val);
}
});
console.log(obj2);