I am getting my ahead around a problem.
I have a JS object which as following:
{
obj:
{
o1:
{
id: "o1",
name: "o1",
fields:
{
f1: { id: "o1:f1", type: { id: "o5" } },
f2: { id: "o1:f2", type: { id: "o2" } },
},
},
o2:
{
id: "o2",
name: "o2",
fields: { f1: { id: "o2:f1", type: { id: "o5" } } },
},
o5: { id: "o5", name: "o5" },
},
}
Within the obj, I have a set of properties deeply nested, each one with an ID which is unique. I want to add, under each parent object (o1, o2, etc), a property from which contains who is referencing the object. A result should look like this:
{
obj:
{
o1:
{
id: "o1",
name: "o1",
fields:
{
f1: { id: "o1:f1", type: { id: "o5" } },
f2: { id: "o1:f2", type: { id: "o2" } },
},
},
o2:
{
id: "o2",
name: "o2",
fields: { f1: { id: "o2:f1", type: { id: "o5" } } },
from: ["o1:f2"],
},
o5: { id: "o5", name: "o5", from: ["o1:f1", "o2:f1"] },
},
}
The from is populated with the id of any fields within each object.
I considered using Ramda which can offer a path or Lodash with a find but I can't solve anyway.
One way to do this is to do a first pass at the object to create something like this:
Then we can simply recursively visit the tree, adding the appropriate
fromnode where we have an element.My version creates this in a round-about way, and I'm quite sure we can improve it. Essentially, we scan the input object with
gather, and create a version that looks like this:Then using a simple
groupByfunction and anObject .entries/Object .fromEntriesdance, we turn this into the above. Then we pass this along with the input to arebuildfunction which immutably adds this to the input object.This version looks like this:
This is working code, but I think it should be updated by fixing
gatherto directly collect the format needed byrebuild. If I had more time, I might try that, but for the moment, I leave this as an exercise for the reader.