I have a datastructure of the form
node: { "name": "root";
"children": [ node ]; }
there is another example at the bottom of the question.
Now I would like to remove all nodes above a specified one and only keep the remaining sub-tree.
So for example, given the tree T
A
/ \
B C
/ \
D E
the function getTree(T, 'C') should return
C
/ \
D E
Question: is there an easy way to implement this?
function getTree(json, node) {
var tree = JSON.parse(json);
/* QUESTION: how do I remove everything not below the node with name===node here?
}
PS: larger example:
var tree = [
{
text: "Parent 1",
nodes: [
{
text: "Child 1",
nodes: [
{
text: "Grandchild 1"
},
{
text: "Grandchild 2"
}
]
},
{
text: "Child 2"
}
]
},
{
text: "Parent 2"
},
{
text: "Parent 3"
},
{
text: "Parent 4"
},
{
text: "Parent 5"
}
];
Edit: good point: I should have mentioned that the node names are unique.
You could iterate the array and look if the node has the wanted text or if the nested nodes have a found.
const
getTree = (tree, text) => {
let result;
tree.some(node => result = node.text === text
? node
: getTree(node.nodes || [], text)
);
return result;
},
tree = [{ text: "Parent 1", nodes: [{ text: "Child 1", nodes: [{ text: "Grandchild 1" }, { text: "Grandchild 2" }] }, { text: "Child 2" }] }, { text: "Parent 2" }, { text: "Parent 3" }, { text: "Parent 4" }, { text: "Parent 5" }];
console.log(getTree(tree, "Grandchild 1"));
console.log(getTree(tree, "Parent 1"));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Related
I would like to generate a tree from the following object:
configuration:
{
name: "General",
icon: "general",
children: [
{
name: "Line 1",
icon: "line",
children: [
{
name: "Area 1",
icon: "area",
children: [
{ name: "Y", icon: "x" },
{ name: "Z", icon: "z" },
],
},
{ name: "Area 2", icon: "line" },
],
},
{
name: "Line 2,
icon: "line",
children: [{ name: "Area 3", icon: "area" }],
},
],
},
In html I have my own custom element:
<my-details>
<div slot="summary"><my-icon name="${icon}"></my-icon> ${name}</div>
${this.children} // ???
</my-details>`;
so I created the function:
createHierarchy() {
if (configuration?.length > 0) {
const details = _configuration.map(({ name, icon }) => {
return ` <my-details>
<div slot="summary"><my-icon name="${icon}"></my-icon> ${name}</div>
${this.children}
</my-details>`;
});
hierarchyContainer.innerHTML = details?.join("");
}
}
but I don't know how to convert this structure in a loop or map to a tree, each element of the hierarchy should be a my-details element and have a name as a slot and in the middle it should have children
the structure should look like this:
hierarchy tree
What you are looking for is a recursive function. Which is a function that calls itself.
It should end up looking something like this:
function parseNode(node) {
let html = `<my-details>
<div slot="summary">
<my-icon name="${node.icon}"></my-icon>
${node.name}.
</div>`;
if(node.children) {
node.children.forEach(childNode => {
html += parseNode(childNode);
})
;}
html += '</my-details>';
return html;
}
parseNode(configuration);
This example turns your entire configuration into an html string (or it should it is untested). You can output to your document/component.
Note that it relies on all nodes having a name and an icon and a possible "children" has to be an array.
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 10 months ago.
I'm trying to manipulate an array like this:
data = [
{
"id":"1",
"items":[
{
"title":"item 1"
},
{
"title":"item 2"
}
]
},
{
"id":"2",
"items":[
{
"title":"item2 1"
},
{
"title":"item2 2"
}
]
}
]
I need, for example, to push another array:
[
{
"title":"item new 1"
},
{
"title":"item new 2"
}
]
inside data[0].items and obtain:
data = [
{
"id":"1",
"items":[
{
"title":"item new 1"
},
{
"title":"item new 2"
}
]
},
{
"id":"2",
"items":[
{
"title":"item2 1"
},
{
"title":"item2 2"
}
]
}
]
...how can I do this maintaining immutability, for example with Lodash?
Not understand anding how to change only a specific sub object in a data structure.
Somebody have suggestions?
Thanks
Presented below is one possible way to immutably add given array into a particular index "items" prop.
Code Snippet
const immutableAdd = (aIdx, addThis, orig) => {
const newData = structuredClone(orig);
newData[aIdx].items = addThis;
return newData;
};
const data = [{
"id": "1",
"items": [{
"title": "item 1"
},
{
"title": "item 2"
}
]
},
{
"id": "2",
"items": [{
"title": "item2 1"
},
{
"title": "item2 2"
}
]
}
];
const addThisArr = [{
"title": "item new 1"
},
{
"title": "item new 2"
}
];
console.log('immutableAdd result: ', immutableAdd(0, addThisArr, data));
console.log('original data: ', data);
.as-console-wrapper { max-height: 100% !important; top: 0 }
Explanation
Use structuredClone() to deep-clone existing data array
Navigate to the aIdx of the cloned-array
Assign the given array (to be added) into aIdx's items prop
NOTE
This solution does not use lodash as it is not mandatory (to use lodash) to perform immutable operations.
If you want to maintain the immutability of original data, just map the content of original data to the new data as you want, and wrap your logic into a pure function to improve readability.
const dataOriginal = [{
"id": "1",
"items": [{
"title": "item 1"
},
{
"title": "item 2"
}
]
},
{
"id": "2",
"items": [{
"title": "item2 1"
},
{
"title": "item2 2"
}
]
}
]
const dataNew = createDataWithSomethingNew(dataOriginal, [{
"title": "item new 1"
},
{
"title": "item new 2"
}
])
function createDataWithSomethingNew(data, props) {
return data.map(function changeItemsOfId1ToProps(value) {
if (value.id === '1') {
return {
id: value.id,
items: props
}
} else {
return value
}
})
}
lodash has a method _.update can modify object with the correct path in string provided.
Another method _.cloneDeep can copy you object deeply. So that change in the pre-copied object will not affect the cloned object.
Finally use a deep freeze function to call Object.freeze recursively on the cloned object to make it immutable.
var data = [
{
"id":"1",
"items":[
{
"title":"item 1"
},
{
"title":"item 2"
}
]
},
{
"id":"2",
"items":[
{
"title":"item2 1"
},
{
"title":"item2 2"
}
]
}
]
var clonedData = _.cloneDeep(data) // copy the full object to avoid modify the source data
// update the data of that path '[0].items' in clonedData
_.update(clonedData, '[0].items', function(n) {
return [
{
"title":"item new 1"
},
{
"title":"item new 2"
}
]
})
// provide object immutability
const deepFreeze = (obj1) => {
_.keys(obj1).forEach((property) => {
if (
typeof obj1[property] === "object" &&
!Object.isFrozen(obj1[property])
)
deepFreeze(obj1[property])
});
Object.freeze(obj1)
};
deepFreeze(clonedData)
data[2] = {id: 3} // data will be changed
data[1].items[2] = {title: "3"} // and also this one
clonedData[2] = {id: 3} // nothing will be changed
clonedData[1].items[2] = {title: "3"} // and also this one
console.log(`data:`, data);
console.log(`clonedData:`, clonedData);
Runkit Example
I have this stackblitz : Tree View
The tree is not building as expected; I want to have something like :
Manager
Sub liste
Manager 1
Manager 2
Manager 3
Can you take a look and give some advices please ?
const TREE_DATA = {
idManager: 1,
label: "Manager",
descendants:
{
idManager: 2,
label: "Sub liste",
descendants: [
{
idManager: 3,
label: "Manager 1"
},
{
idManager: 4,
label: "Manager 2"
},
{
idManager: 5,
label: "Manager 3"
}
]
}
};
Change your TREE_DATA structure
How would i go about rendering a menu with nested <ul> items with an an unknown amount of children in react from an object like in the following example?
[
{
title: "Top level 1",
slug: "top-level-1",
children: [
{
title: "Sub level 1",
slug: "sub-level-1",
children: [
{
title: "Sub Sub Level 1"
slug: "sub-sub-level-1"
}
]
}
{
title: "Sub level 2",
slug: "sub-level-2"
}
]
},
{
title: "Top level 2",
slug: "top-level 2"
}
]
Codesandbox example
You just have to recursively call Menu component for its children to display and pass as a data prop.
let data = [
{
title: "Top level 1",
slug: "top-level-1",
children: [
{
title: "Sub level 1",
slug: "sub-level-1",
children: [
{
title: "Sub Sub Level 1",
slug: "sub-sub-level-1",
children: [
{
title: "Sub Sub Level 2",
slug: "sub-sub-level-2"
}
]
}
]
},
{
title: "Sub level 2",
slug: "sub-level-2"
}
]
},
{
title: "Top level 2",
slug: "top-level 2"
}
];
const Menu = ({data}) => {
return (
<ul>
{data.map(m => {
return (<li>
{m.title}
{m.children && <Menu data={m.children} />}
</li>);
})}
</ul>
);
}
const App = () => (
<div style={styles}>
<Hello name="CodeSandbox" />
<h2>Start editing to see some magic happen {'\u2728'}</h2>
<Menu data={data} />
</div>
);
You could recursively Render the component for nested data which has variable depth.
Sample Snippet.
var data = [
{
title: "Top level 1",
slug: "top-level-1",
children: [
{
title: "Sub level 1",
slug: "sub-level-1",
children: [
{
title: "Sub Sub Level 1",
slug: "sub-sub-level-1"
}
]
},
{
title: "Sub level 2",
slug: "sub-level-2"
}
]
},
{
title: "Top level 2",
slug: "top-level 2"
}
]
const MyComponent = (props) => {
if(Array.isArray(props.collection)) {
return <ul>
{props.collection.map((data)=> {
return <li>
<ul>
<li>{data.title}</li>
<li>{data.slug}</li>
<li><MyComponent collection={data.children}/></li>
</ul>
</li>
})
}
</ul>
}
return null;
}
class App extends React.Component {
render() {
return (
<MyComponent collection={data}/>
)
}
}
ReactDOM.render(<App/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
P.S. The snippet contains formatting errors, but I am sure you will be able to rectify that. Snippet was to give an idea of the approach
How would I split the following AJAX response into three separate objects based on the attribute 'product_range' using JS/jQuery, i.e. one object array for all 'range-1' products, one for 'range-2' and so on?
[
{
title: "Product 1",
price: "12.00",
product_range: "range-1"
},
{
title: "Product 2",
price: "12.00",
product_range: "range-2"
},
{
title: "Product 3",
price: "12.00",
product_range: "range-3"
}
]
I would just use reduce and push items into an object that holds arrays.
var items = [
{
title: "Product 1",
price: "12.00",
product_range: "range-1"
},
{
title: "Product 2",
price: "12.00",
product_range: "range-2"
},
{
title: "Product 3",
price: "12.00",
product_range: "range-3"
}
];
var grouped = items.reduce( function (obj, item) {
if (!obj[item.product_range]) obj[item.product_range] = [];
obj[item.product_range].push(item);
return obj;
}, {});
console.log(grouped);
console.log(grouped["range-1"]);
Use the method "filterByProductRange" to filter out the data by product_range.
var obj = [
{
title: "Product 1",
price: "12.00",
product_range: "range-1"
},
{
title: "Product 2",
price: "12.00",
product_range: "range-2"
},
{
title: "Product 3",
price: "12.00",
product_range: "range-3"
}
];
function filterByProductRange(data, product_range) {
return data.filter(function(item) { return item['product_range'] == product_range; });
}
var range1= filterByProductRange(obj, 'range-1');
console.log(range1);
if you mean grouping your data by product_range, then:
//json is your json data
var result = {};
for(var i=0; i<json.length;i++)
{
if(result[json[i].product_range] === undefined) result[json[i].product_range] = [];
result[json[i].product_range].push(json[i]);
}
Something like this should group by range.
var ranged = {};
var data = [{
title: "Product 1",
price: "12.00",
product_range: "range-1"
}, {
title: "Product 2",
price: "12.00",
product_range: "range-2"
}, {
title: "Product 3",
price: "12.00",
product_range: "range-3"
}]
$.each(data, function(i, x) {
if (ranged[x.product_range]) {
ranged[x.product_range].push(x);
} else {
ranged[x.product_range] = [x];
}
});
console.log(JSON.stringify(ranged));
You should then be able to retrieve all object for a given range by querying the ranged object.
You can use $.map() to achieve a similar result.
var range1 = new Object(),
range2 = new Object(),
range3 = new Object();
$.map(data, function(d){
if (d.product_range === "range-1") {
for (var i in d) {
range1[i] = d[i];
}
}
});
Where data is your object array.
Here's a simple fiddle to demonstrate this.