Getting Name of Parent Object from Value of Object

Javascript objects: get parent

No. There is no way of knowing which object it came from.

s and obj.subObj both simply have references to the same object.

You could also do:

var obj = { subObj: {foo: 'hello world'} };
var obj2 = {};
obj2.subObj = obj.subObj;
var s = obj.subObj;

You now have three references, obj.subObj, obj2.subObj, and s, to the same object. None of them is special.

Getting name of parent object from value of object

Just use Object.keys() and find()

var obj = {        'John': {'phone':'7326', 'age': '23'},        'Paul': {'phone': '9898', 'age': '12'},        'Lucy': {'phone': '1122', 'age': '24'}}
const res = Object.keys(obj).find(e => obj[e].phone === '9898');console.log(res);

Get parent object from key or its value in a nested object

This can be done using a recursive function.


const paths = {
"path": "./parent",
"name": "parent",
"type": "folder",
"children": [
{
"path": "./parent/child1",
"name": "child1",
"type": "folder",
"children": [
{
"path": "./parent/child1/file1",
"name": "file1",
"size": 651956838,
"extension": ".pdf",
"type": "file"
},
{
"path": "./parent/child1/file2",
"name": "file2",
"size": 468327031,
"extension": ".pdf",
"type": "file"
}
]
},
{
"path": "./parent/child2",
"name": "child2",
"type": "folder",
"children": [
{
"path": "./parent/child2/file3",
"name": "file1",
"size": 651956838,
"extension": ".pdf",
"type": "file"
},
{
"path": "./parent/child2/file4",
"name": "file2",
"size": 468327031,
"extension": ".pdf",
"type": "file"
}
]
}
]
}

const pathtofind = "./parent/child1";

function findChildrenInPath(object, path) {
if (path.startsWith(object.path)) {
if (object.path == path) {
return object.children;
}
else {
for (let child of object.children) {
const result = findChildrenInPath(child, path);
if (result) {
return result;
}
}
}
}
}

const res = findChildrenInPath(paths, pathtofind);
console.log(res);

javascript get name of parent object/variable

One way;

var myObject = {
'myFunction' : function () {
for (var name in window) {
if (window[name] === this) {
alert(name);
break;
}
}
}
}

Not very nice IMO, marginally better if you wrap it in your own namespace.

You could also always

var myObject = {
moniker: "myObject",
...

In light of your update you don't need to resolve the object at all;

var myObject = {
'intval' : '',
'timeout' : 1500,
'start' : function () {
var self = this;
this.intval = window.setInterval(function() {
self.myFunction()
}, this.timeout);
},
'myFunction' : function() {
alert(this.intval);
}
}


Related Topics



Leave a reply



Submit