java script filling up an array so it matches following structure - javascript

lets say i want to start with empty value of variable data, how can to achieve this result with javascript using push method:
var data = [
{
label: 'node1',
children: [
{ label: 'child1' },
{ label: 'child2' }
]
},
{
label: 'node2',
children: [
{ label: 'child3' }
]
}
];
i have tried:
data.push("label: nodel", "children:"+ ['child1', 'child2']);
looking at code above i need to insert one element that will be linked with list of childs. Can someone help me achieve this.. i would be very grateful.
Best regards.

Is this what you mean?
var object1 = {
label: 'node1',
children: [
{ label: 'child1' },
{ label: 'child2' }
]
};
var data = new Array();
data.push(object1);
OR
data.push({ label: 'node1', children: [ { label: 'child1' }, { label: 'child2' } ] });
EDITED TO SHOW YOSHIS VERSION ASWELL

Related

how can i change array of object to object of array in javascript?

I am trying to convert array of objects to object of array using javascript.
Here is the code
const data = [
{
items: [
{
code: "location_list_page",
icon: "environment",
id: 1,
link: "/configurations/locations",
name: "Localisations",
}
]
},
{
items: [
{
code: "service_list_page",
icon: "api",
id: 5,
link: "/configurations/services",
name: "Services",
}
]
}
]
I want to create this object:
const data = {
items: [
{
code: "location_list_page",
icon: "environment",
id: 1,
link: "/configurations/locations",
name: "Localisations",
},
{
code: "service_list_page",
icon: "api",
id: 5,
link: "/configurations/services",
name: "Services",
}
]
}
I try to solve it using map in array method but it didn't work.
Anyone can help me please ???
This is a pretty straightforward use of flatMap:
const data = [
{
items: [
{
code: "location_list_page",
icon: "environment",
id: 1,
link: "/configurations/locations",
name: "Localisations",
}
]
},
{
items: [
{
code: "service_list_page",
icon: "api",
id: 5,
link: "/configurations/services",
name: "Services",
}
]
}
]
const result = {items: data.flatMap(x => x.items)};
console.log(result);
it can be solved using map function and Object.assign() and the spread operator
var new_data = {"items": data.map(x=> Object.assign({}, ...x["items"]))};

MongoDB - MongooseJS - Retrieve ID from parent to set child in collection

I am currently working in an app which the data is persisted in MongoDB using the MongooseJS.
There is a collection: DataRoomFolder. The documents have the following structure:
{
id,
isFolder,
name,
parentId: ObjectId(parent-DataRoomFolder),
projectId,
...
}
For each model Project, there is linked different DataRoomFolder but by default, when it is created, it will add a schema already predefined which I already have:
[
{
label: '01-Architecture',
items: [
{ label: 'Design', items: [] },
{ label: 'Drawings', items: [] },
],
},
{
label: '02-Permits',
items: [{ label: 'Building Permit', items: [] }],
},
{
label: '02-Permits',
items: [{ label: 'Building Permit', items: [] }],
},
{
label: '03-Control office',
items: [
{ label: 'Construction', items: [
{ label: 'Calculation reports', items: [] },
{ label: 'Datasheets', items: [] },
{ label: 'Drawings', items: [] },
{ label: 'Hand-over reports', items: [] },
{ label: 'Maintenance checklists', items: [] },
{ label: 'One-line diagrams', items: [] },
{ label: 'Technical notices', items: [] },
] },
{ label: 'Environment', items: [] },
{ label: 'Safety', items: [
{ label: 'Calculation reports', items: [] },
{ label: 'Datasheets', items: [] },
{ label: 'Drawings', items: [] },
{ label: 'Hand-over reports', items: [] },
{ label: 'Maintenance checklists', items: [] },
{ label: 'One-line diagrams', items: [] },
{ label: 'Technical notices', items: [] },
] },
],
}
As you can see, there is parent-children reference.
The question: when I loop for each to create every folder, I need to create have first the parent folder saved to get the ID and parsed to the children.
I saw a workaround with Populate but it does not fit my needs.
How should I persist to get parent IDs and carrying on adding to the children and saving and not getting affected the performance?
Thanks!

How can I loop in an multi-dimensional array to get the capture the the last node using spread operator

Consider this example. I am trying to move to first element of 2-D ARRAY which contains two array items and use spread operator until I get text inside the inner most array.
let arr = [
[ {
type: 'paragraph',
children: [{ text: 'First line.' }],
},
{
type: 'paragraph',
children: [{ text: 'Second.' }],
}
],[
{
type: 'paragraph',
children: [{ text: 'Third.' }],
},
{
type: 'paragraph',
children: [{ text: 'Fourth.' }],
}
]
]
//const newArr = [...arr[0]] // more logic
//result to ['first line','Second.']
JS Fiddle to test the array
I dont think the spread operator will be of any help here, but consider this:
let arr = [
[ {
type: 'paragraph',
children: [{ text: 'First line.' }],
},
{
type: 'paragraph',
children: [{ text: 'Second.' }],
}
],[
{
type: 'paragraph',
children: [{ text: 'Third.' }],
},
{
type: 'paragraph',
children: [{ text: 'Fourth.' }],
}
]
]
let result1 = [];
arr.flat().forEach(element => result1.push(element.children[0].text));
console.log("Result1:", result1);
// or just group the children from arr[0] together:
let result2 = [];
arr[0].forEach(element => result2.push(element.children[0]));
console.log("Result2:", result2);

Flatten a deeply nested array with objects and arrays

I have an array of objects that contain another array with objects. The nesting is four levels deep.
The structure of the array is:
[
{
title: 'Title',
type: 'section',
links: [
{
label: 'Label',
id: 'id_1',
links: [
{
title: 'Title',
type: 'section',
links: [
{
label: 'Label',
id: 'id_2',
links: [
{
label: 'Label',
id: 'id_3',
links: [],
}
]
}
]
},
{
title: 'Other title',
type: 'section',
links: [
{
label: 'Label',
id: 'id_4',
links: [],
}
]
}
]
}
]
}
]
I want to have a flattened array with the id's of the link arrays that contain links (they are parents of submenu's).
So the desired outcome is like:
["id_1", "id_2"]
I have tried to get the outcome with this function taken from MDN:
flatDeep(arr, d = 1) {
return d > 0
? arr.reduce((acc, val) =>
acc.concat(Array.isArray(val.links)
? this.flatDeep(val.links, d - 1)
: val.links), [])
: arr.slice();
}
This gives me an empty array.
Use Array.flatMap(). Destructure each object and use an empty array as default for missing id values. Concat the id and the result of flattening the links recursively.
const flattenIds = arr => arr.flatMap(({ id = [], links }) =>
[].concat(id, flattenIds(links))
);
const data = [{ title: 'Title', type: 'section', links: [{ label: 'Label', id: 'id_1', links: [{ title: 'Title', type: 'section', links: [{ label: 'Label', id: 'id_2', links: [{ label: 'Label', id: 'id_3', links: [] }] }] }, { title: 'Other title', type: 'section', links: [{ label: 'Label', id: 'id_4', links: [] }] }] }] }];
const result = flattenIds(data);
console.log(result);
You could get a flat array with a recursion and a check for id for missing property.
const
getId = ({ id, links }) => [
...(id === undefined ? [] : [id]),
...links.flatMap(getId)
],
data = [{ title: 'Title', type: 'section', links: [{ label: 'Label', id: 'id_1', links: [{ title: 'Title', type: 'section', links: [{ label: 'Label', id: 'id_2', links: [{ label: 'Label', id: 'id_3', links: [] }] }] }, { title: 'Other title', type: 'section', links: [{ label: 'Label', id: 'id_4', links: [] }] }] }] }],
result = data.flatMap(getId);
console.log(result);
Here is a non-recursive version.
const data = [{title:'Title',type:'section',links:[{label:'Label',id:'id_1',links:[{title:'Title',type:'section',links:[{label:'Label',id:'id_2',links:[{label:'Label',id:'id_3',links:[]}]}]},{title:'Other title',type:'section',links:[{label:'Label',id:'id_4',links:[]}]}]}]}];
const stack = data.slice();
const result = [];
let obj;
while (obj = stack.shift()) {
if ("id" in obj && obj.links.length > 0) result.push(obj.id);
stack.push(...obj.links);
}
console.log(result);
This uses breath first, but can easily be changed into depth first. You'll only have to change the stack.push call into stack.unshift.
For a more detailed explanation about the two, check out Breadth First Vs Depth First.
var array = JSON.parse('[{"title":"Title","type":"section","links":[{"label":"Label","id":"id_1","links":[{"title":"Title","type":"section","links":[{"label":"Label","id":"id_2","links":[{"label":"Label","id":"id_3","links":[]}]}]},{"title":"Other title","type":"section","links":[{"label":"Label","id":"id_4","links":[]}]}]}]}]');
arr = [];
while(array.length != 0) {
var ob1 = array.splice(0,1)[0];
for(var ob2 of ob1.links) {
if (ob2.links.length !== 0) {
arr.push(ob2.id);
array = array.concat(ob2.links);
}
}
}
console.log(arr);
Here's the output as you requested:
[
"id_1",
"id_2"
]
I think recursive function will simplify. (recursively look for lists array and push the id into res).
const data = [
{
title: "Title",
type: "section",
links: [
{
label: "Label",
id: "id_1",
links: [
{
title: "Title",
type: "section",
links: [
{
label: "Label",
id: "id_2",
links: [
{
label: "Label",
id: "id_3",
links: []
}
]
}
]
},
{
title: "Other title",
type: "section",
links: [
{
label: "Label",
id: "id_4",
links: []
}
]
}
]
}
]
}
];
const res = [];
const ids = data => {
data.forEach(item => {
if ("id" in item) {
res.push(item.id);
}
if (item.links) {
ids(item.links);
}
});
};
ids(data);
console.log(res);

Javascript array with a mix of literals and arrays

How can I create an json format in javascript
var data = [
{
label: 'node1',
children: [
{ label: 'child1' },
{ label: 'child2' }
]
},
{
label: 'node2',
children: [
{ label: 'child3' }
]
}
]
I can add the 'node' using data.push, but how to proceed with childrens?
Thank's!
First off, there is no such thing as a JSON array. You are working with an array. JSON is a way to transfer data between systems.
You have an array called data that you need to push an object into...
so something like:
data.push({
label: 'node3',
children: [
{ label: 'child3' },
{ label: 'child3' }
]
});
Now.. you've got a problem at this point, because you are duplicating the label property, which is not allowed under ES5 strict mode.

Categories

Resources