insert in subdocument with mongoDB - javascript

I have the following document in the collection:
"_id" : "2",
"workspace" : [{
"name" : "1",
"widgets" : [ ]
},{
"name" : "2",
"widgets" : [ ]
},{
"name" : "3",
"widgets" : [ ]
},{
"name" : "4",
"widgets" : [ ]
}
]}
How can I insert {id: "1", blabla: "blabla"} in "widgets" for the "name" 3?

In comparison to a previous answer which just inserts everything into the root of the document, here is a correct way to do this with positional operator:
db.t.update({
"_id" : "2",
"workspace.name" : "3"
},{
$push: {
'workspace.$.widgets' : {
id: "2",
blabla: "blabla"
}
}
});

Related

How to delete array element from JSON array of objects by ID

This is probably quite easy, but giving me trouble. Given this JSON structure:
"playlists" : [
{
"id" : "1",
"owner_id" : "2",
"song_ids" : [
"8",
"32"
]
},
{
"id" : "2",
"owner_id" : "3",
"song_ids" : [
"6",
"8",
"11"
]
},
{
"id" : "3",
"owner_id" : "7",
"song_ids" : [
"7",
"12",
"13",
"16",
"2"
]
}
]
How would you delete an object from the array by key/value? In this case by ID? playlist.splice(1,1)? playlist.delete(id)? Not sure how to do this elegantly. Let's say I wish to delete the element with ID = 3, how to get this result:
"playlists" : [
{
"id" : "1",
"owner_id" : "2",
"song_ids" : [
"8",
"32"
]
},
{
"id" : "2",
"owner_id" : "3",
"song_ids" : [
"6",
"8",
"11"
]
}
]
Using Array.filter, you can filter out elements that don't match a certain condition. For example:
const result = playlists.filter(playlist => playlist.id !== '2');
Here's a working demo:
/* Example Data */
const playlists = [
{
"id" : "1",
"owner_id" : "2",
"song_ids" : [ "8", "32"]
},
{
"id" : "2",
"owner_id" : "3",
"song_ids" : ["6", "8","11" ]
}
];
/* Takes a list of playlists, and an ID to remove */
const removePlaylistById = (plists, id) =>
plists.filter(playlist => playlist.id !== id);
/* Removes playlist ID 2 from list, prints result */
const result = removePlaylistById(playlists, '2');
console.log(result);
Another option, would be to use Array.findIndex to get the index of an element with given ID, then use Array.splice to remove that element. This will modify the array, without the need for a copy.
For example:
const indexToRemove = playlists.findIndex((pl) => pl.id === '2');
playlists.splice(indexToRemove, 1);

How to return the variant values of each product if that product is a variant?

I have a database in MongoDB like this
{"productId" : 1,
"isVariant": 1,
"variantId" : 1,
"attributeSet" : [
{
"name" : "Capacity",
"value" : "500 GB",
"id" : 3
},
{
"name" : "Form Factor",
"value" : "5 inch",
"id" : 4
},
{
"id" : 5,
"name" : "Memory Components",
"value" : "3D NAND"
}
]
},
{"productId" : 2,
"isVariant": 1,
"variantId" : 1,
"attributeSet" : [
{
"name" : "Capacity",
"value" : "1 TB",
"id" : 3
},
{
"name" : "Form Factor",
"value" : "5 inch",
"id" : 4
},
{
"id" : 5,
"name" : "Memory Components",
"value" : "3D NAND"
}
]
},
{"productId" : 3,
"isVariant": 1,
"variantId" : 1,
"attributeSet" : [
{
"name" : "Capacity",
"value" : "500 GB",
"id" : 3
},
{
"name" : "Form Factor",
"value" : "2.5 inch",
"id" : 4
},
{
"id" : 5,
"name" : "Memory Components",
"value" : "3D NAND"
}
]
},
{"productId" : 4,
"isVariant": 1,
"variantId" : 1,
"attributeSet" : [
{
"name" : "Capacity",
"value" : "1 TB",
"id" : 3
},
{
"name" : "Form Factor",
"value" : "2.5 inch",
"id" : 4
},
{
"id" : 5,
"name" : "Memory Components",
"value" : "3D NAND"
}
]
}
Now I want to return data where 500 GB has been in productId 1 and 3
The response should be like this:
variantValues : [{
attributeValue : "500 GB",
data : [
{productId : 1},
{productId : 3}
]},
{
attributeValue : "1 TB",
data : [
{productId : 2},
{productId : 4}
]},
{
attributeValue : "2.5 inch",
data : [
{productId : 3},
{productId : 4}
]},
{
attributeValue : "5 inch",
data : [
{productId : 1},
{productId : 2}
]}]
I have the possible values that I store in another collection for variantPossible values. The values that i am storing are like this:
"VariantValues" : {
"3" : [
"500 GB",
"1 TB"
],
"4" : [
"2.5 inch",
"5 inch"
]
},
I want to return the variant values of each product if that product is a variant with the above format. can anyone help me with this.
You should be able to achieve this using $unwind and $group in your aggregation pipeline. This first flattens each attribute into a single document and on those you can group by the attribute value.
Finally, you can use $project to get the desired name for attributeValue:
db.collection.aggregate([
{
$unwind: "$attributeSet"
},
{
$group: {
_id: "$attributeSet.value",
data: {
"$addToSet": {
productId: "$productId"
}
}
}
},
{
"$project": {
_id: 0,
data: 1,
attributeValue: "$_id"
}
}
])
See this simplifed example on mongoplayground: https://mongoplayground.net/p/VASadZnDedc

Need to remove duplication in array of objects and merge array with union USING JS

Need to remove duplication in array of objects and merge array with union USING JS.
trying to filter array
Just wanted to merge array["INTERFACE"] on the basis of APP_ID. and remove duplicate records.
unfiltered unmerged array!
var data = [
{
"APP_ID" : "1001",
"INTERFACE" : [
{
"INTERFACE_ID" : "01",
"NAME" : "CIF OPENNING",
"URL" : "/CusIdInfo",
"STATUS" : "A"
},
{
"INTERFACE_ID" : "07",
"NAME" : "DASHBOARD",
"URL" : "/Dashboard",
"STATUS" : "A"
},
{
"INTERFACE_ID" : "06",
"NAME" : "SUMMARY COPC",
"URL" : "/SummaryCopc",
"STATUS" : "A"
}
]
},
{
"APP_ID" : "1002",
"INTERFACE" : [
{
"INTERFACE_ID" : "07",
"NAME" : "DASHBOARD",
"URL" : "/Dashboard",
"STATUS" : "A"
},
{
"INTERFACE_ID" : "08",
"NAME" : "BIOMETRIC",
"URL" : "/Biometric",
"STATUS" : "A"
}
]
},
{
"APP_ID" : "1001",
"INTERFACE" : [
{
"INTERFACE_ID" : "01",
"NAME" : "CIF OPENNING",
"URL" : "/CusIdInfo",
"STATUS" : "A"
},
{
"INTERFACE_ID" : "05",
"NAME" : "SUMMARY",
"URL" : "/Summary",
"STATUS" : "A"
},
{
"INTERFACE_ID" : "06",
"NAME" : "SUMMARY COPC 2",
"URL" : "/SummaryCopc2",
"STATUS" : "A"
},
{
"INTERFACE_ID" : "07",
"NAME" : "DASHBOARD 2",
"URL" : "/Dashboard 2",
"STATUS" : "A"
}
]
},
{
"APP_ID" : "1002",
"INTERFACE" : [
{
"INTERFACE_ID" : "07",
"NAME" : "DASHBOARD",
"URL" : "/Dashboard",
"STATUS" : "A"
},
{
"INTERFACE_ID" : "08",
"NAME" : "BIOMETRIC",
"URL" : "/Biometric",
"STATUS" : "A"
}
]
}
];
wanted result
[
{
"APP_ID" : "1002",
"INTERFACE" : [
{
"INTERFACE_ID" : "07",
"NAME" : "DASHBOARD",
"URL" : "/Dashboard",
"STATUS" : "A"
},
{
"INTERFACE_ID" : "08",
"NAME" : "BIOMETRIC",
"URL" : "/Biometric",
"STATUS" : "A"
}
]
},
{
"APP_ID" : "1001",
"INTERFACE" : [
{
"INTERFACE_ID" : "01",
"NAME" : "CIF OPENNING",
"URL" : "/CusIdInfo",
"STATUS" : "A"
},
{
"INTERFACE_ID" : "05",
"NAME" : "SUMMARY",
"URL" : "/Summary",
"STATUS" : "A"
},
{
"INTERFACE_ID" : "06",
"NAME" : "SUMMARY COPC",
"URL" : "/SummaryCopc",
"STATUS" : "A"
},
{
"INTERFACE_ID" : "07",
"NAME" : "DASHBOARD",
"URL" : "/Dashboard",
"STATUS" : "A"
}, {
"INTERFACE_ID" : "07",
"NAME" : "DASHBOARD 2",
"URL" : "/Dashboard2",
"STATUS" : "A"
},
{
"INTERFACE_ID" : "06",
"NAME" : "SUMMARY COPC 2",
"URL" : "/SummaryCopc2",
"STATUS" : "A"
}
]
}
]
trying to filter array
Just wanted to merge array["INTERFACE"] on the basis of APP_ID. and remove duplicate records.
Here is a slightly elastic solution relying on function generators that allows dynamic aggregation.
The logic followed by the below example is that in your data input, the unique key of the main objects is APP_ID. Next, the aggregation rule of each APP_ID is that it should follow another aggregation rule for INTERFACE. Each interface, in fact, has a unique NAME, explaining why you have multiple "07" and "06" in your result sample.
The code explanation is documented in the code itself.
var data = [
{
"APP_ID" : "1001",
"INTERFACE" : [
{
"INTERFACE_ID" : "01",
"NAME" : "CIF OPENNING",
"URL" : "/CusIdInfo",
"STATUS" : "A"
},
{
"INTERFACE_ID" : "07",
"NAME" : "DASHBOARD",
"URL" : "/Dashboard",
"STATUS" : "A"
},
{
"INTERFACE_ID" : "06",
"NAME" : "SUMMARY COPC",
"URL" : "/SummaryCopc",
"STATUS" : "A"
}
]
},
{
"APP_ID" : "1002",
"INTERFACE" : [
{
"INTERFACE_ID" : "07",
"NAME" : "DASHBOARD",
"URL" : "/Dashboard",
"STATUS" : "A"
},
{
"INTERFACE_ID" : "08",
"NAME" : "BIOMETRIC",
"URL" : "/Biometric",
"STATUS" : "A"
}
]
},
{
"APP_ID" : "1001",
"INTERFACE" : [
{
"INTERFACE_ID" : "01",
"NAME" : "CIF OPENNING",
"URL" : "/CusIdInfo",
"STATUS" : "A"
},
{
"INTERFACE_ID" : "05",
"NAME" : "SUMMARY",
"URL" : "/Summary",
"STATUS" : "A"
},
{
"INTERFACE_ID" : "06",
"NAME" : "SUMMARY COPC 2",
"URL" : "/SummaryCopc2",
"STATUS" : "A"
},
{
"INTERFACE_ID" : "07",
"NAME" : "DASHBOARD 2",
"URL" : "/Dashboard 2",
"STATUS" : "A"
}
]
},
{
"APP_ID" : "1002",
"INTERFACE" : [
{
"INTERFACE_ID" : "07",
"NAME" : "DASHBOARD",
"URL" : "/Dashboard",
"STATUS" : "A"
},
{
"INTERFACE_ID" : "08",
"NAME" : "BIOMETRIC",
"URL" : "/Biometric",
"STATUS" : "A"
}
]
}
];
// Aggregate duplicates with a common uniqueKey, invoking the aggregateExpression callback for each pair.
function* aggregateDuplicates(arr, uniqueKey, aggregateExpression) {
const aggregateGroups = arr.reduce((acc,next) => {
acc[next[uniqueKey]] = acc[next[uniqueKey]] || [];
return acc[next[uniqueKey]].push(next), acc;
}, {});
// loop items.
for (var [_, entries] of Object.entries(aggregateGroups)) {
// Aggregate results following the aggregateExpression.
yield Object.assign({}, entries.reduce((acc, next) => aggregateExpression(acc, next)));
}
}
// Aggregate duplicates of data, whose unique key is APP_ID.
const res = [...aggregateDuplicates(data, 'APP_ID', (a,b) => {
// In order to properly aggregate the INTERFACE property, acquire the set of entires interfaces of two items with the same APP_ID.
var interfacesSet = [...a.INTERFACE, ...b.INTERFACE];
// Finally, spread common values between them, then aggregate the INTERFACE property by its unique NAME key.
return Object.assign(a, b, {
INTERFACE: [...aggregateDuplicates(interfacesSet, 'NAME', (c,d) => {
// For that NAME property, just assign the values of both objects, nothing more nothing less.
return Object.assign(c,d)
})]
});
})];
console.log(res);
SIDE NOTE: The sorting to the INTERFACE property is not applied, this is a plus, but I don't think it's mandatory as long as the output data is effectively correct.
// Create the array of APP_ID
let idArr = data.map(val => val.APP_ID)
// Remove duplicate APP_ID
idArr = [...new Set(idArr)];
// Filter data according to unique APP_IDs
let newArr = idArr.map(val => {
return data.filter(value => value.APP_ID == val)[0]
})
console.log(newArr);
Solution
Here is a quick solution that I was able to come up with,
Note that this solution takes care of union of INTERFACES within the same APP_ID
const data = [
{
APP_ID: '1001',
INTERFACE: [
{
INTERFACE_ID: '01',
NAME: 'CIF OPENNING',
URL: '/CusIdInfo',
STATUS: 'A',
},
{
INTERFACE_ID: '07',
NAME: 'DASHBOARD',
URL: '/Dashboard',
STATUS: 'A',
},
{
INTERFACE_ID: '06',
NAME: 'SUMMARY COPC',
URL: '/SummaryCopc',
STATUS: 'A',
},
],
},
{
APP_ID: '1002',
INTERFACE: [
{
INTERFACE_ID: '07',
NAME: 'DASHBOARD',
URL: '/Dashboard',
STATUS: 'A',
},
{
INTERFACE_ID: '08',
NAME: 'BIOMETRIC',
URL: '/Biometric',
STATUS: 'A',
},
],
},
{
APP_ID: '1001',
INTERFACE: [
{
INTERFACE_ID: '01',
NAME: 'CIF OPENNING',
URL: '/CusIdInfo',
STATUS: 'A',
},
{
INTERFACE_ID: '05',
NAME: 'SUMMARY',
URL: '/Summary',
STATUS: 'A',
},
{
INTERFACE_ID: '06',
NAME: 'SUMMARY COPC 2',
URL: '/SummaryCopc2',
STATUS: 'A',
},
{
INTERFACE_ID: '07',
NAME: 'DASHBOARD 2',
URL: '/Dashboard 2',
STATUS: 'A',
},
],
},
{
APP_ID: '1002',
INTERFACE: [
{
INTERFACE_ID: '07',
NAME: 'DASHBOARD',
URL: '/Dashboard',
STATUS: 'A',
},
{
INTERFACE_ID: '08',
NAME: 'BIOMETRIC',
URL: '/Biometric',
STATUS: 'A',
},
],
},
];
const result = {};
data.forEach(elem => {
if (!result[elem.APP_ID]) {
result[elem.APP_ID] = {};
result[elem.APP_ID].APP_ID = elem.APP_ID;
result[elem.APP_ID].INTERFACE = elem.INTERFACE;
} else {
const interfaces = result[elem.APP_ID].INTERFACE;
for (const elemInterface of elem.INTERFACE) {
if (
!interfaces.some(inter => {
return elemInterface.INTERFACE_ID === inter.INTERFACE_ID;
})
) {
interfaces.push(elemInterface);
}
}
}
});
console.log('TCL: results', Object.values(result));
Assumptions:
Since you stated that you wanted union of the interfaces within the same APP_ID I assume that there should be no duplicate interfaces
Example: If there is an interface array A1,
[
{
INTERFACE_ID: '01',
NAME: 'CIF OPENNING',
URL: '/CusIdInfo',
STATUS: 'A',
},
{
INTERFACE_ID: '07',
NAME: 'DASHBOARD',
URL: '/Dashboard',
STATUS: 'A',
},
{
INTERFACE_ID: '06',
NAME: 'SUMMARY COPC',
URL: '/SummaryCopc',
STATUS: 'A',
},
]
and another interface array A2,
[
{
INTERFACE_ID: '01',
NAME: 'CIF OPENNING',
URL: '/CusIdInfo',
STATUS: 'A',
},
{
INTERFACE_ID: '05',
NAME: 'SUMMARY',
URL: '/Summary',
STATUS: 'A',
},
{
INTERFACE_ID: '06',
NAME: 'SUMMARY COPC 2',
URL: '/SummaryCopc2',
STATUS: 'A',
},
{
INTERFACE_ID: '07',
NAME: 'DASHBOARD 2',
URL: '/Dashboard 2',
STATUS: 'A',
},
]
Then A1 union A2 would be,
[
{
"INTERFACE_ID": "01",
"NAME": "CIF OPENNING",
"URL": "/CusIdInfo",
"STATUS": "A"
},
{
"INTERFACE_ID": "07",
"NAME": "DASHBOARD",
"URL": "/Dashboard",
"STATUS": "A"
},
{
"INTERFACE_ID": "06",
"NAME": "SUMMARY COPC",
"URL": "/SummaryCopc",
"STATUS": "A"
},
{
"INTERFACE_ID": "05",
"NAME": "SUMMARY",
"URL": "/Summary",
"STATUS": "A"
}
]
Note that there are no duplicates.
My second assumption is that when you check for duplicity in interfaces you use the INTERFACE_ID and not the whole interface object.
Example: Assume an interface object I1,
{
INTERFACE_ID: '01',
NAME: 'CIF OPENNING',
URL: '/CusIdInfo',
STATUS: 'A',
}
and another interface object I2 with the only difference being that it has a different status value which is 'B',
{
INTERFACE_ID: '01',
NAME: 'CIF OPENNING',
URL: '/CusIdInfo',
STATUS: 'B',
}
I am still considering I1 and I2 to be duplicates based on their INTERFACE_ID.
Suppose you want to compare entire object for duplicity then update your question and I shall change the answer to factor it in
Came up with this solution. Hope this works for you.
NOTE : In the expected result array you have 2 interface objects with same ID so i am assuming that two interface are duplicate only if all their properties match.
var data = [
{
"APP_ID" : "1001",
"INTERFACE" : [
{
"INTERFACE_ID" : "01",
"NAME" : "CIF OPENNING",
"URL" : "/CusIdInfo",
"STATUS" : "A"
},
{
"INTERFACE_ID" : "07",
"NAME" : "DASHBOARD",
"URL" : "/Dashboard",
"STATUS" : "A"
},
{
"INTERFACE_ID" : "06",
"NAME" : "SUMMARY COPC",
"URL" : "/SummaryCopc",
"STATUS" : "A"
}
]
},
{
"APP_ID" : "1002",
"INTERFACE" : [
{
"INTERFACE_ID" : "07",
"NAME" : "DASHBOARD",
"URL" : "/Dashboard",
"STATUS" : "A"
},
{
"INTERFACE_ID" : "08",
"NAME" : "BIOMETRIC",
"URL" : "/Biometric",
"STATUS" : "A"
}
]
},
{
"APP_ID" : "1001",
"INTERFACE" : [
{
"INTERFACE_ID" : "01",
"NAME" : "CIF OPENNING",
"URL" : "/CusIdInfo",
"STATUS" : "A"
},
{
"INTERFACE_ID" : "05",
"NAME" : "SUMMARY",
"URL" : "/Summary",
"STATUS" : "A"
},
{
"INTERFACE_ID" : "06",
"NAME" : "SUMMARY COPC 2",
"URL" : "/SummaryCopc2",
"STATUS" : "A"
},
{
"INTERFACE_ID" : "07",
"NAME" : "DASHBOARD 2",
"URL" : "/Dashboard 2",
"STATUS" : "A"
}
]
},
{
"APP_ID" : "1002",
"INTERFACE" : [
{
"INTERFACE_ID" : "07",
"NAME" : "DASHBOARD",
"URL" : "/Dashboard",
"STATUS" : "A"
},
{
"INTERFACE_ID" : "08",
"NAME" : "BIOMETRIC",
"URL" : "/Biometric",
"STATUS" : "A"
}
]
}
];
isInterfaceDuplicate = function(interface, app_id) {
var keys = Object.keys(interface);
var isDuplicate = false;
app_map[app_id].forEach(app_obj => {
var matched = true;
keys.forEach(key => {
if (interface[key] !== app_obj[key]) {
matched = false;
return;
}
});
if (matched) {
isDuplicate = true;
return;
}
});
return isDuplicate;
};
/* Create a mapping for APP_ID and INTERFACE */
var app_map = {};
data.forEach(app_obj => {
// If APP_ID is not present in map, then add in map directly.
if (!app_map[app_obj.APP_ID]) {
app_map[app_obj.APP_ID] = [...app_obj.INTERFACE];
return;
}
// If APP_ID is present in map, only add non duplicate interfaces in APP_ID key.
app_obj.INTERFACE.forEach(interface => {
var isDuplicate = isInterfaceDuplicate(interface, app_obj.APP_ID);
if (!isDuplicate) {
app_map[app_obj.APP_ID].push({...interface});
}
});
});
/* Create result array from the map */
var result = [];
Object.keys(app_map).forEach(app_id => {
result.push({
"APP_ID": app_id,
"INTERFACE": app_map[app_id]
});
});
console.log(result);

Join two collection in mongoDB and extract out data in node js

I am using MongoDB 3.6 for my project.
I have 2 collections "users" and "follow". I want to extract out details of user's followers and following (like an Instagram app).
users collection
{
"id" : "1",
"name" : "abc",
"age" : "26"
},
{
"id" : "2",
"name" : "xyz",
"age" : "22"
},
{
"id" : "3",
"name" : "qwe",
"age" : "23"
}
follow collection
{
"id" : "2",
"follow id" : "1"
},
{
"id" : "3",
"follow id" : "1"
},
{
"id" : "1",
"follow id" : "2"
},
{
"id" : "2",
"follow id" : "3"
},
{
"id" : "1",
"follow id" : "3"
}
Now i want following list of id 2 So id 2 is following id 1 and id 3
So, Output should be like this
{
"id" : "1",
"name" : "abc",
"age" : "26"
},
{
"id" : "3",
"name" : "qwe",
"age" : "23"
}
For that, I am using $lookup aggregation. But this is not giving the desired output which I want.
Here is my code -
Follow.aggregate([
{
$lookup:{
from:"users",
localField:"id",
foreignField:"id",
as:"fromItems"
}
},
{
$replaceRoot:{newRoot: {$mergeObjects: [ { $arrayElemAt: ["$fromItems", 0 ] }, "$$ROOT" ] } }
},
{ $project :
{
fromItems : 0
}
}
], callback)
For more understanding please refer the image
To get following list of id 2 you can use following query:
Follow.aggregate([
{
$match: { "id": "2" }
},
{
$lookup:{
from:"users",
localField:"follow id",
foreignField:"id",
as:"fromItems"
}
},
{
$replaceRoot:{newRoot: {$mergeObjects: [ { $arrayElemAt: ["$fromItems", 0 ] }, "$$ROOT" ] } }
},
{ $project :
{
id : "$follow id",
name: 1,
age: 1
}
}
])
So the point here is that you have a relation between id and follow id and after $lookup phase follow id becomes the new id since it's parent-child relation.
EDIT:
3.4 solution below
Follow.aggregate([
{
$match: { "id": "2" }
},
{
$lookup:{
from:"users",
localField:"follow id",
foreignField:"id",
as:"fromItems"
}
},
{
$project: {
id: "$follow id",
from: { $arrayElemAt: ["$fromItems", 0 ] }
}
},
{ $project :
{
id : 1,
name: "$from.name",
age: "$from.age"
}
}
])

D3 tree/hierachical related data between nodes

I am working on a d3 project at the moment, and I am trying to map out a hierachical tree to show people and who they are responsible for. Basically I can user A and user B and they can each be responsible for the same person.
Currently to highlight this in my JSON data that builds the visualisation I am repeating data, is there away to not repeat data and use the same data point when 2 or more people are responsible for the same person?
Here is my JSfiddle example
My Hierachical Visualisation
You will see here that, Raymond Reddington & Donald Ressler have cross over between some of their responsibilites, I am repeating the data which seems inefficient, is there a better way, here is my JSON.
[
{
"name" : "Company Name",
"parent" : null,
"children": [
{
"name" : "Raymond Reddington",
"parent" : "Cherry Tree Lodge",
"children" : [
{
"name" : "Debe Zuma",
"parent" : "Raymond Reddington",
},
{
"name" : "Tom Keen",
"parent" : "Raymond Reddington",
},
{
"name" : "Aram Mojtabai",
"parent" : "Raymond Reddington",
}
]
},
{
"name" : "Elizabeth Keen",
"parent" : "Cherry Tree Lodge",
"children" : [
{
"name" : "Samar Navabi",
"parent" : "Elizabeth Keen",
},
{
"name" : "Meera Malik",
"parent" : "Elizabeth Keen",
},
{
"name" : "Mr. Kaplan",
"parent" : "Elizabeth Keen",
},
{
"name" : "Reven Wright",
"parent" : "Elizabeth Keen",
}
]
},
{
"name" : "Donald Ressler",
"parent" : "Cherry Tree Lodge",
"children" : [
{
"name" : "Matius Solomon",
"parent" : "Donald Ressler",
"size" : 3938
},
{
"name" : "Peter Kotsiopulos",
"parent" : "Donal Ressler",
"size" : 3938
},
{
"name" : "Tom Keen",
"parent" : "Raymond Reddington",
"size" : 3938
},
{
"name" : "Aram Mojtabai",
"parent" : "Raymond Reddington",
"size" : 3938
}
]
},
{
"name" : "Harold Cooper",
"parent" : "Cherry Tree Lodge",
"children" : [
{
"name" : "Samar Navabi",
"parent" : "Elizabeth Keen",
"size" : 3938
},
{
"name" : "Meera Malik",
"parent" : "Elizabeth Keen",
"size" : 3938
}
]
}
]
}
]
This website details a method of converting flat data to the hierarchical data required by d3 http://www.d3noob.org/2014/01/tree-diagrams-in-d3js_11.html
They explain it well too. As the author notes it is originally based on https://stackoverflow.com/a/17849353/1544886
I have copied and pasted their website's example below:
var data = [
{ "name" : "Level 2: A", "parent":"Top Level" },
{ "name" : "Top Level", "parent":"null" },
{ "name" : "Son of A", "parent":"Level 2: A" },
{ "name" : "Daughter of A", "parent":"Level 2: A" },
{ "name" : "Level 2: B", "parent":"Top Level" }
];
will map to:
var treeData = [
{
"name": "Top Level",
"parent": "null",
"children": [
{
"name": "Level 2: A",
"parent": "Top Level",
"children": [
{
"name": "Son of A",
"parent": "Level 2: A"
},
{
"name": "Daughter of A",
"parent": "Level 2: A"
}
]
},
{
"name": "Level 2: B",
"parent": "Top Level"
}
]
}
];
via:
var dataMap = data.reduce(function(map, node) {
map[node.name] = node;
return map;
}, {});
var treeData = [];
data.forEach(function(node) {
// add to parent
var parent = dataMap[node.parent];
if (parent) {
// create child array if it doesn't exist
(parent.children || (parent.children = []))
// add node to child array
.push(node);
} else {
// parent is null or missing
treeData.push(node);
}
});
You could extend that further replacing with Ids and using a second normalised array for the lookup:
[{
"id": 0,
"name": "Cherry Tree Lodge"
},{
"id": 1,
"name": "Tom Keen"
},{
"id": 2,
"name": "Debe Zuma"
}]
Also please note that your json data is not strictly valid, you have extra commas.

Categories

Resources