Let's say I have some Javascript with the following:
Foo = {
alpha: { Name: "Alpha", Description: "Ipso Lorem" },
bravo: { Name: "Bravo", Description: "Nanu, Nanu" },
delta: { Name: "Fly with me", Description: "Klaatu barata nikto" }
};
Table = [ Foo.alpha, Foo.bravo, Foo.delta];
x = Table[1];
Is there any way of looking at x and getting the identifier bravo? I'm fully aware that I can use x.Name or x.Description, but let's say that I need to know the name for something elsewhere. In one task I experimented with, I was forced to add a redundant id : "bravo" to each entry, but that was a pain.
My gut tells me it can't be done. But I'm hoping someone else can tell me otherwise.
Foo = {
alpha: { Name: "Alpha", Description: "Ipso Lorem" },
bravo: { Name: "Bravo", Description: "Nanu, Nanu" },
delta: { Name: "Fly with me", Description: "Klaatu barata nikto" }
};
Table = [ ];
for(let val in Foo){
let obj = Foo[val];
obj = {...obj , id:val }
Table.push(obj)
}
x = Table[1];
console.log(x)
Personally, I'd use a Proxy ...
const _Foo = {
alpha: { Name: "Alpha", Description: "Ipso Lorem" },
bravo: { Name: "Bravo", Description: "Nanu, Nanu" },
delta: { Name: "Fly with me", Description: "Klaatu barata nikto" }
};
const Foo = new Proxy(_Foo, {
get(target, id) {
if (target.hasOwnProperty(id)) {
return {...target[id], id};
}
return target[id];
}
});
const Table = [ Foo.alpha, Foo.bravo, Foo.delta ];
console.log(Table[0])