I am working on a group project where we have a rover which has Raspberry Pi (Python) sending the location in coordinates to a javascript webpage. I can successfully create a simple echo python server and javascript client but want to learn how We can keep the client and server running where the Server is giving out coordinates of the rover continuously to the javascript client till Rover reaches its destination and the connection closes.
Category: javascript
Category Added in a WPeMatico Campaign
firebase admin or normal firebase with next js
I am working on next js project and I use it with firebase and right now I use firebase with my components to retrieve some data and it works perfectly – as expected – and I wanted to use firebase in getServerSideProps so I thought I should use firebase admin sdk but for fun I tried to use it with the same firebase package I used on front end and – I don’t know how – it worked however the code in getServerSideProps must be a back end code so right now I don’t know why does it work and If I should keep using firebase web package or switch to firebase admin package
Pass data from JS to Python via Django
I want to send data from python to JS in Django. I successfully see the data in the response in the browser, but JS returns as empty string. What would be the reason?
trying to fetch information;
def XXX(request):
message_id=request.POST.get('messageid')
return render(request, 'XX.html')
sender;
y = json.loads(response.text)
ts = str(y["file"]["shares"]["public"]["XX"][0]["ts"])
return render (request, 'problemduyurusucreate.html', {'ts':ts})
JS;
...
var test = "{{ ts }}";
$.ajax({
type: "POST",
url: "{% url 'slack' %}",
data: {
"messageid": test,
csrfmiddlewaretoken: '{{ csrf_token }}'
}
...
but I am displaying in my browser that I have successfully pulled the data
How would I log the hash values in this API response?
I’m new to javascript and I was wondering how I would access the hash value and return the string so I can log it? Here’s my code, I’m using axios.
Here’s my code:
client.on("messageCreate", (message) => {
const args = message.content.slice(prefix.length).trim().split(' ')
const command = args.shift().toLowerCase();
if (command === 'search') {
let termargs = args.join(" ");
const options = {
method: 'GET',
url: 'https://breachdirectory.p.rapidapi.com/',
params: { func: 'auto', term: termargs},
headers: {
'x-rapidapi-host': 'breachdirectory.p.rapidapi.com',
'x-rapidapi-key': (keytouse, keys[keytouse]),
}
};
message.reply("searching...")
options.params.term = termargs
axios.request(options).then(function (response) {
console.log('Found:' , response.data["result"]);
}).catch(function (error) {
message.reply(JSON.stringify(error));
});
}
});
client.login(TOKEN);
Here’s what it returns:
Found:
[
{ has_password: false, sources: [ 'Pluto.tv' ] },
{
has_password: true,
password: 'bleh',
hash: 'kMUX9351bsMjbgXH9rpKKf+GIYJrJy4=',
sources: [ 'Aptoide.com' ]
},
{
has_password: true,
password: 'blah',
hash: 'lEiyXSecP9cIGJfyYhs8yteVEplUIRjAvaI7Jc76upI=',
sources: [ 'Collection 1' ]
},
{
has_password: true,
password: 'blahblahblah',
hash: 'djdrICyb/EfH6+R0g/26+d+GIYJrJy6j',
sources: 'Unverified'
}
]
I tried doing response.data.results.hash but that didn’t work. Any help would be appreciated. Thank you!
Dynamic routes not working for any routes besides ‘/’
import React from "react";
import { Home, Profile, Saved, Explore, Auth, Settings } from "./pages";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
const App = () => {
const routes = [
{ path: "/", component: Home },
{ path: "/profile/:id", component: Profile },
{ path: "/saved", component: Saved },
{ path: "/explore", component: Explore },
{ path: "/auth", component: Auth },
{ path: "/settings", component: Settings },
];
return (
<div className="bg-gray-200 w-full min-h-screen">
<Router>
<Switch>
{" "}
{routes.map((route, i) => {
return <Route key={i} exact path={route.path} component={route.component} />;
})}{" "}
</Switch>
</Router>
</div>
);
};
I can’t seem to figure this out. If I make the first path dynamic it works. But the rest of the Routes don’t work when I try and make them dynamic. Am I missing something, I checked around and looked at tutorials but couldn’t find anything I would be missing
Two out put Combine array in Javascript with under score
Var a = "837297,870895"
Var b = "37297,36664"
OutPut = "837297_37297,870895_36664
I tried multiple script but does not working
Why is my XML not being Formatted Properly?
I have been handed a chunk of code from a developer that no longer works for us, and I am new to the regex game so to speak, so apologies if the answer seems simple.
the goal is to format an XML response into something that is readable and here is the code I have been presented with:
formatXml: function (xml) {
if (xml.indexOf('<') == -1) {
return xml;
}
//remove all white spaces
xml = xml.replace(/>s+|s+</g, function (m) {
return m.trim();
});
// remove extra variables
xml = xml.substring(xml.indexOf('<'), (xml.lastIndexOf('>') + 1));
var formatted = '';
var reg = /(>)(<)(/*)/g;
xml = xml.replace(reg, '$1rn$2$3');
var pad = 0;
jQuery.each(xml.split('rn'), function (index, node) {
var indent = 0;
if (node.match(/.+</w[^>]*>$/)) {
indent = 0;
} else if (node.match(/^</w/)) {
if (pad != 0) {
pad -= 1;
}
} else if (node.match(/^<w[^>]*[^/]>.*$/)) {
indent = 1;
} else {
indent = 0;
}
var padding = '';
for (var i = 0; i < pad; i++) {
padding += ' ';
}
formatted += padding + node + 'rn';
pad += indent;
});
return formatted;
}
The xml
that is sent into this looks something like the following portion:
"\u003cns3:oadrPayload\n\t\t\t\t\txmlns\u003d\"http://www.w3.org/2000/09/xmldsig#\" \n\t\t\t\t\txmlns:ns2\u003d\"http://docs.oasis-open.org/ns/energyinterop/201110\" \n\t\t\t\t\txmlns:ns3\u003d\"http://openadr.org/oadr-2.0b/2012/07\" \n\t\t\t\t\txmlns:ns4\u003d\"http://docs.oasis-open.org/ns/energyinterop/201110/payloads\" \n\t\t\t\t\txmlns:ns5\u003d\"urn:ietf:params:xml:ns:icalendar-2.0\" \n\t\t\t\t\txmlns:ns6\u003d\"urn:ietf:params:xml:ns:icalendar-2.0:stream\" xmlns:ns7\u003d\"http://www.w3.org/2005/Atom\" \n\t\t\t\t\txmlns:ns8\u003d\"http://docs.oasis-open.org/ns/emix/2011/06/power\" \n\t\t\t\t\txmlns:ns9\u003d\"http://www.opengis.net/gml/3.2\" \n\t\t\t\t\txmlns:ns10\u003d\"http://docs.oasis-open.org/ns/emix/2011/06\" \n\t\t\t\t\txmlns:ns11\u003d\"http://docs.oasis-open.org/ns/emix/2011/06/siscale\" \n\t\t\t\t\txmlns:ns12\u003d\"http://www.w3.org/2009/xmldsig11#\" \n\t\t\t\t\txmlns:ns13\u003d\"http://openadr.org/oadr-2.0b/2012/07/xmldsig-properties\" \n\t\t\t\t\txmlns:ns14\u003d\"urn:un:unece:uncefact:codelist:standard:5:ISO42173A:2010-04-07\"\u003e\n\t\t\t\t\t\u003cns3:oadrSignedObject\u003e\n\t\t\t\t\t\t\u003cns3:oadrResponse ns2:schemaVersion\u003d\"2.0b\"\u003e\n\t\t\t\t\t\t\t\u003cns2:eiResponse\u003e\n\t\t\t\t\t\t\t\t\u003cns2:responseCode\u003e200\u003c/ns2:responseCode\u003e\n\t\t\t\t\t\t\t\t\u003cns2:responseDescription\u003eOK\u003c/ns2:responseDescription\u003e\n\t\t\t\t\t\t\t\t\u003cns4:requestID\u003e123456789abc\u003c/ns4:requestID\u003e\n\t\t\t\t\t\t\t\u003c/ns2:eiResponse\u003e\n\t\t\t\t\t\t\u003c/ns3:oadrResponse\u003e\n\t\t\t\t\t\u003c/ns3:oadrSignedObject\u003e\n\t\t\t\t\u003c/ns3:oadrPayload\u003e"
and what is being returned is this:
"u003cns3:oadrPayloadntttttxmlnsu003d"http://www.w3.org/2000/09/xmldsig#" ntttttxmlns:ns2u003d"http://docs.oasis-open.org/ns/energyinterop/201110" ntttttxmlns:ns3u003d"http://openadr.org/oadr-2.0b/2012/07" ntttttxmlns:ns4u003d"http://docs.oasis-open.org/ns/energyinterop/201110/payloads" ntttttxmlns:ns5u003d"urn:ietf:params:xml:ns:icalendar-2.0" ntttttxmlns:ns6u003d"urn:ietf:params:xml:ns:icalendar-2.0:stream" xmlns:ns7u003d"http://www.w3.org/2005/Atom" ntttttxmlns:ns8u003d"http://docs.oasis-open.org/ns/emix/2011/06/power" ntttttxmlns:ns9u003d"http://www.opengis.net/gml/3.2" ntttttxmlns:ns10u003d"http://docs.oasis-open.org/ns/emix/2011/06" ntttttxmlns:ns11u003d"http://docs.oasis-open.org/ns/emix/2011/06/siscale" ntttttxmlns:ns12u003d"http://www.w3.org/2009/xmldsig11#" ntttttxmlns:ns13u003d"http://openadr.org/oadr-2.0b/2012/07/xmldsig-properties" ntttttxmlns:ns14u003d"urn:un:unece:uncefact:codelist:standard:5:ISO42173A:2010-04-07"u003entttttu003cns3:oadrSignedObjectu003enttttttu003cns3:oadrResponse ns2:schemaVersionu003d"2.0b"u003entttttttu003cns2:eiResponseu003enttttttttu003cns2:responseCodeu003e200u003c/ns2:responseCodeu003enttttttttu003cns2:responseDescriptionu003eOKu003c/ns2:responseDescriptionu003enttttttttu003cns4:requestIDu003e123456789abcu003c/ns4:requestIDu003entttttttu003c/ns2:eiResponseu003enttttttu003c/ns3:oadrResponseu003entttttu003c/ns3:oadrSignedObjectu003enttttu003c/ns3:oadrPayloadu003e"
But it should be this:
"<ns3:oadrPayload
xmlns="http://www.w3.org/2000/09/xmldsig#"
xmlns:ns2="http://docs.oasis-open.org/ns/energyinterop/201110"
xmlns:ns3="http://openadr.org/oadr-2.0b/2012/07"
xmlns:ns4="http://docs.oasis-open.org/ns/energyinterop/201110/payloads"
xmlns:ns5="urn:ietf:params:xml:ns:icalendar-2.0"
xmlns:ns6="urn:ietf:params:xml:ns:icalendar-2.0:stream" xmlns:ns7="http://www.w3.org/2005/Atom"
xmlns:ns8="http://docs.oasis-open.org/ns/emix/2011/06/power"
xmlns:ns9="http://www.opengis.net/gml/3.2"
xmlns:ns10="http://docs.oasis-open.org/ns/emix/2011/06"
xmlns:ns11="http://docs.oasis-open.org/ns/emix/2011/06/siscale"
xmlns:ns12="http://www.w3.org/2009/xmldsig11#"
xmlns:ns13="http://openadr.org/oadr-2.0b/2012/07/xmldsig-properties"
xmlns:ns14="urn:un:unece:uncefact:codelist:standard:5:ISO42173A:2010-04-07">
<ns3:oadrSignedObject>
<ns3:oadrResponse ns2:schemaVersion="2.0b">
<ns2:eiResponse>
<ns2:responseCode>200</ns2:responseCode>
<ns2:responseDescription>OK</ns2:responseDescription>
<ns4:requestID>123456789abc</ns4:requestID>
</ns2:eiResponse>
</ns3:oadrResponse>
</ns3:oadrSignedObject>
</ns3:oadrPayload>"
Why is it that the regex in formatXml
doesn’t remove all of the escaped characters and the “” characters?
Also, what can I add in to this to be able to replace the u003d
with =
, u003c
with <
, and u003e
with >
?
Search database stored in .txt file format?
-
Solutions I could think of using Python and Pandas to get the records out and store them Postgres. Then search the database. That would be ideal.
-
Another would be to use javascript to search the text data records without extracting them.
Not a best practice.
Which brings me to my question: Is there a clean way to extract databases stored in text files using Python?
How to create a Generic CRUD service in Nodejs via TypeORM
I am attempting to create a generic service that should take a ‘given’ Entity to perform basic CRUD operations.
Thus far, I have tried:
export type UserEntity<E> = { new (): E } | Function;
class AuthenticationService<E> {
private userEntity: UserEntity<E>;
constructor(userEntity: UserEntity<E>) {
this.userEntity = userEntity;
}
async login(email: string, password: string) {
// const user = await getRepository(this.userEntity).findOneOrFail({ email });
const user = await this.userEntity?.findOneOrFail({ email });
const validPassword = argon2.verify(user?.password, password);
if (!validPassword) {
throw new ErrorHandler(401, ErrorMessage.INVALID_EMAIL_PASSWORD);
}
const accessToken = JWTHelpers.generateToken(user, {
secret: config.ACCESS_TOKEN_SECRET,
expiry: '300s',
});
const refreshToken = JWTHelpers.generateToken(user, {
secret: config.REFRESH_TOKEN_SECRET,
expiry: '1y',
});
user.tokens = user.tokens.concat(refreshToken);
await user.save();
Reflect.deleteProperty(user, 'password');
return { accessToken, refreshToken };
}
This approach doesn’t seem to work and as a result, compiler throws various types of errors – for instance:
-
Property 'findOneOrFail' does not exist on type 'UserEntity<E>'. Property 'findOneOrFail' does not exist on type 'Function'.
Which is thrown from this declaration:
const user: E = await this.userEntity?.findOneOrFail({ email });
-
Property 'password' does not exist on type 'NonNullable<E>'.
–
thrown at:const validPassword = argon2.verify(user?.password, password);
I am very open to suggestions on how to best approach / fix these issues.
Thanks in advance.
How to make function work only for one button? Bootstrap-5 scroll to modals bottom
What I want to achieve is to create two buttons:
1: that opens modal window
2: opens same modal and scrolls to bottom
code:
$('#menu-item-6706').on('click', function (){
$('#exampleModal').on('shown.bs.modal', function (event) {
$("#exampleModal .modal-body").animate({ scrollTop: $('#exampleModal .modal-body').prop("scrollHeight")}, 'slow');
});
});
Here is full jsfiddle snippet: https://jsfiddle.net/mkx2auhj/1/
Script is almost working:
If you trigger for the the first time “launch demo modal” it opens modal.
If you trigger “Contact” it opens modal and scrolls to bottom. So it’s correct.
The problem is if you hit “launch demo modal” again it scrolls to bottom again, which is not desirable. I want it to open standard modal like the first time.
Reactjs change state (color) onMouseDown
CONTEXT: I have this matrix which is mainly made of some instances of a react component i’ve created earlier called “Cell”. Each time a cell is clicked it changes it’s state.color to red.
Problem: Looking for an approach to turn them red onMouseDown ( as you’re making a square translucent selection in windows explorer) besides onClick
Cell.js :
import * as React from 'react';
class Cell extends React.Component {
state = {
color: '#bbdefb',
};
onChange = () => {
this.setState({color: 'red'});
};
render() {
return (
<div
style={{
backgroundColor: this.state.color,
display: 'inline-block',
width: 20,
height: 20,
opacity: '60%',
outlineStyle: 'solid',
inlineStyle: 'solid',
outlineWidth: '1px',
inlineWidth: '1px',
outlineColor: '#1a237e',
}}
onClick={this.onChange}
/>
);
}
}
export default Cell;
Main.js :
import {Box} from '@mui/material';
import * as React from 'react';
import MathGrid from '../../core/Components/MathGrid/MathGrid';
import Cell from './Cell';
// =====================================================================================================================
// D E C L A R A T I O N S
// =====================================================================================================================
const ROWS = 7;
const COLUMNS = 10;
const PADDING = 8;
const SX = {
root: {
width: '100%',
height: '100%',
},
footer: {
position: 'absolute',
backgroundColor: 'red',
display: 'flex',
left: PADDING,
top: '70%',
right: PADDING,
height: '100px',
},
counter: {
position: 'absolute',
top: '50%',
left: '50%',
},
matrix: {
position: 'absolute',
left: PADDING,
top: 0,
right: PADDING,
bottom: PADDING,
},
math1: {
height: '100%',
width: '100%',
backgroundPosition: 'calc(50% + 10px) calc(50% + 10px)',
pointerEvents: 'none',
},
};
// =====================================================================================================================
// C O M P O N E N T
// =====================================================================================================================
const generateMatrix = () => {
return [
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
];
};
class Main extends React.PureComponent {
state = {matrix: generateMatrix()};
render() {
const matrix = this.state.matrix;
const rows = [];
for (let i = 0; i < matrix.length; i++) {
for (let j = 1; j < matrix.length / 2; j++) {
if (i > j) {
rows.push(this.renderRow(matrix[i], i));
}
}
}
return (
<Box sx={SX.root}>
<Box sx={SX.matrix}>{rows}</Box>
</Box>
);
}
// -----------------------------------------------------------------------------------------------------------------
// I N T E R N A L
// -----------------------------------------------------------------------------------------------------------------
renderRow = (row, index) => {
console.log(row);
const cells = [];
for (let i = 0; i < row.length; i++) {
cells.push(<Cell key={i} />);
}
return <Box key={index}>{cells}</Box>;
};
}
// =====================================================================================================================
// E X P O R T
// =====================================================================================================================
export default Main;
`Duplex.from()` throws `The “iterable” argument must be an instance of Iterable. Received an instance of Object`
Im highly confused. The Duplex.from()
method can take a object as src
and creates fromt he object properties readable
& writable
a duplex stream:
converts
readable
andwritable
into Stream and then combines them into Duplex where the Duplex will write to the writable and read from the readable.
Why does my example not work?
const { PassThrough, Duplex } = require("stream");
const loopback = new PassThrough();
const duplex = Duplex.from({
writable: loopback,
readable: loopback
});
duplex.on("data", (chunk) => {
console.log("Data on duplex", chunk)
});
duplex.write("Hello World");
My expected outcome is that the a duplex stream is created, and if so, that outputs the same i give as input. (Same as “echo”, or plain passthrough stream)
Error message:
[nodemon] starting `node index.js`
internal/streams/from.js:32
throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable);
^
TypeError [ERR_INVALID_ARG_TYPE]: The "iterable" argument must be an instance of Iterable. Received an instance of Object
at new NodeError (internal/errors.js:322:7)
at from (internal/streams/from.js:32:11)
at Function.Readable.from (internal/streams/readable.js:1368:10)
at Object.<anonymous> (/home/marc/projects/test-stream/index.js:7:23)
at Module._compile (internal/modules/cjs/loader.js:1085:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
at Module.load (internal/modules/cjs/loader.js:950:32)
at Function.Module._load (internal/modules/cjs/loader.js:790:12)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:75:12)
at internal/main/run_main_module.js:17:47 {
code: 'ERR_INVALID_ARG_TYPE'
}
Can some one explain to my why i cant create a duplex stream from the a object?
Im a bit lost, since the docs say you can pass a object as argument, but the error message says “must be an instance of Iterable”. As far as i know, a object is iterable. So whats the problem here?
Can’t get For loop to execute more than once
I have several links on my page and a function that generates the preview of each one like this:
Its supposed to loop and generate the preview for each link but it only does it one. Why is that?
function parselinks() {
var links = document.getElementsByClassName('linkprev');
for(var link of links) {
if(link.innerHTML =='') {
var data = {key: 'fe2964d7c80ef2b8f6ba046ae9e8c0a5', q: link.getAttribute('href') }
fetch('https://api.linkpreview.net', {
method: 'POST',
mode: 'cors',
body: JSON.stringify(data),
}).then(res => res.json()).then(response => {
var linktitle = response.title;
var linkdesc = response.description;
var linkimg = response.image;
link.innerHTML = `
<span><img src="${linkimg}" alt=""></span>
<h2>${linktitle}</h2>
<br>
<p>${linkdesc}</p>
`;
})
}
}
}
parselinks();
img {width:100px;}
span {
float: left;
}
span, h2, p {
font-size: 15px;
line-height: 80%;
}
<a href="https://yahoo.com" class="linkprev"></a>
<a href="https://facebook.com" class="linkprev"></a>
<a href="https://twitter.com" class="linkprev"></a>
<a href="https://instagram.com" class="linkprev"></a>
How can I iterate over an element in an array but not move from the index until a condition is fulfill?
Hi fam happy Valentine’s.
I’m not looking for a code solution but some insights about how could I go about iterating over an array let’s call it array = [1, 1, 1], and not moving to the next element in the array until a condition is fulfilled. For example I want to start at index 0 and only go to the next index (1) after the value of such index is (modified/changed) to be greater than the value of the index before it. At 0 index we have the value 1, I want before moving to index 1 to change the value of index 1 to be greater then the value of index 0. Something like this if we have array = [1, 1, 1] I want to iterate over the array, start at 0 index. Compare if the value of 0 index is greater or equal than the value of index 1 (the next index) If so than add 1 to the value of index 1 until that value is greater than the value of index 0. First iteration we get array = [1, 2, 1].
Next iteration we get array = [1, 2, 3].
At this point I have tried to iterate over the array with a for loop grab each element, compare and add 1 to the element but when I get to the last element it does not add anything since I am at the end of the array and there is no item to loop over. I get array = [1, 2, 2] Please help fam. This is what I have so far.
// array
const array = [1, 1, 1]
// iterating over array
for (let i = 0; i < array.length; i++) {
// compare
if (array[i] >= array[i + 1]) {
// increase next number by 1
array[i + 1] += 1
}
}
How to display nested leafs in a Chart.js Treemap?
I want to display data in chart.js as a nested treemap using chartjs-chart-treemap.
Everything works fine with flat / single-depth data, but I am having trouble understanding how to make a hierarchical structure work.
I’ve studied the examples but they’ve not given me any clear insight.
Simplified, the data I have is:
- A (50% through children)
- C (25% through children)
- C1 (12.5% through children)
- C1a: 6.25%
- C1b: 6.25%
- C2: 12.5%
- C1 (12.5% through children)
- D: 25%
- C (25% through children)
- B: 50%
This should give a Treemap similar to this:
+-------+------+-------+------+
| C1a | | |
+-------+ C2 | |
| C1b | | |
+-------+------+ B +
| | |
| D | |
| | |
+-------+------+-------+------+
The only thing I have found is to keep adding groups
:
[
{"name": "A", "l0": "/", "l1": "A", "l2": "", "l3": "", "l4": "", "value": 0},
{"name": "B", "l0": "/", "l1": "B", "l2": "", "l3": "", "l4": "", "value": 50},
{"name": "C", "l0": "/", "l1": "A", "l2": "C", "l3": "", "l4": "", "value": 0},
{"name": "C1", "l0": "/", "l1": "A", "l2": "C", "l3": "C1", "l4": "", "value": 0},
{"name": "C1a", "l0": "/", "l1": "A", "l2": "C", "l3": "C1", "l4": "C1a", "value": 6.25},
{"name": "C1b", "l0": "/", "l1": "A", "l2": "C", "l3": "C1", "l4": "C1b", "value": 6.25},
{"name": "C2", "l0": "/", "l1": "A", "l2": "C", "l3": "C2", "l4": "", "value": 12.5},
{"name": "D", "l0": "/", "l1": "A", "l2": "D", "l3": "", "l4": "", "value": 25}
]
But that looks like a hack to me, which would indicate that there is probably a better way to do this?
What I have thus far is:
const data = [
{name: "A", l0: "/", l1: "A", l2: "", l3: "", l4: "", value: 0},
{name: "B", l0: "/", l1: "B", l2: "", l3: "", l4: "", value: 50},
{name: "C", l0: "/", l1: "A", l2: "C", l3: "", l4: "", value: 0},
{name: "C1", l0: "/", l1: "A", l2: "C", l3: "C1", l4: "", value: 0},
{name: "C1a", l0: "/", l1: "A", l2: "C", l3: "C1", l4: "C1a", value: 6.25},
{name: "C1b", l0: "/", l1: "A", l2: "C", l3: "C1", l4: "C1b", value: 6.25},
{name: "C2", l0: "/", l1: "A", l2: "C", l3: "C2", l4: "", value: 12.5},
{name: "D", l0: "/", l1: "A", l2: "D", l3: "", l4: "", value: 25},
];
const ctx = document.querySelector('canvas').getContext("2d");
let config = {
type: 'treemap',
data: {
datasets: [{
tree: data, key: 'value',
groups: ['l0', 'l1', 'l2', 'l3', 'l4', 'name'],
}]
},
};
new Chart(ctx, config);
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chartjs-chart-treemap.min.js"></script>
<canvas></canvas>
Is there a better way than just adding groups to achieve nested leafs in the treemap?