How can I dynamically add values to my typescript array? - arrays

I'm trying to dynamically populate my pieChartColors array, so that in the end my array will look something like this:
public pieChartColors:Array<Color> = [
{
backgroundColor: '#141C48'
},
{
backgroundColor: '#FF0000'
},
{
backgroundColor: '#EFEFEF'
},
...
]
I'm starting with a blank array and have tried a few different ways to get the values added, but none of them are working (my color values are stored without the hash symbol):
public pieChartColors: Array<Color> = [];
public buildPieChart() {
...
for (let pie of pieData) {
// none of these work
this.pieChartColors.push(backgroundColor: '#'+pie.backgroundColor);
this.pieChartColors.backgroundColor.push('#'+pie.backgroundColor);
this.pieChartColors['backgroundColor'].push('#'+pie.backgroundColor);
}
...
}
BTW, pieData is an object I'm looping through from the database with the backgroundColor values. If I console.log the pie.backgroundColor, the value is available.

Just do it like in JavaScript:
this.pieChartColors.push({backgroundColor: '#'+pie.backgroundColor});

Related

Resolving simple references in a spreadsheet structure. Is this a linked list problem?

I have this job test task where I am need some help.
I have to somehow dynamically access the value in the data stucture below, through references. To this point I used loops and indexOf() in an ordered alphabet and numbers. indexOf("B") in alphabet is [[ 1 ]], indexOf(1) is [0] for the two dimensional array.
Here "B1" is referencing "C1", "C1" references "D1" .. to "H1" and when "H1" points to the text "Last", all of the formulas should turn into the same value - the text "Last".
But how? Been breaking my head for a couple of hours and remembered linked lists, but so far have no clue how to implement them. How can I achieve this?
{
data: [
[
{ reference: "B1" },
{ reference: "C1" },
{ reference: "D1" },
{ reference: "E1" },
{ reference: "F1" },
{ reference: "G1" },
{ reference: "H1" },
{ text: "Last" },
]
],
id: "job-20"
}
It looks like you need to work with a spreadsheet type of data structure, and need to recalculate cells based on the formulas they have.
You can use recursion for that.
The base case happens when you arrive at a cell that has no reference. In that case the text of that cell can be returned to the caller. And that caller will assign that text to the cell it was looking at, and also returns that to their caller...etc.
function get(reference) { // return the cell object at the given reference
return data[reference.slice(1)-1][reference.charCodeAt() - "A".charCodeAt()];
}
function resolve(cell, visited=new Set) {
// Have we found a cell with just text? Then return that to caller
if (!("reference" in cell)) return cell.text;
// Did we already meet this cell before? Then we are running in circles!
if (visited.has(cell)) return "Circular Reference!";
// Make a recursive call to know what the text should be
cell.text = resolve(get(cell.reference), visited.add(cell));
delete cell.reference;
return cell.text; // Return this value also to the caller
}
function calculate(data) {
// Get to each cell object...
for (let row of data) {
for (let cell of row) {
resolve(cell); // And update its text property by following references
}
}
}
let data = [
[
{reference: "B1"}, {reference: "C1"}, {reference: "D1"}, {reference: "E1"},
{reference: "F1"}, {reference: "G1"}, {reference: "H1"}, {text: "Last"},
]
];
calculate(data);
console.log(data);
It should be noted that in a real spreadsheet the references (formulas) are not deleted during such a recalculation. The cell will have both the text and the reference, so that when a cell's text is updated, all other dependent cells get their own text updated accordingly again.

Populate and array from another one

I'm new to angular and typescript and I have an issue.
I have an array that I create and I want to implement properties and values to this array from another one but when I try to do so, the array length stay to one, for example I want to add properties longueur and quantity depending on the values from the second array but here's what I get :
Array that needs to be implemented
I do a forEach on an Array to get the elements I want to implements in the array but doesn't seems to work ( maybe I do it not in the proper way )
Array that populate the other one with longueur and quantity
So basically, my array length should be the same as the one that populates it ( array in first picture should be lenght of 22, each index having longueur and quanitity from the other array ).
Here's my code sample :
component.ts :
quotDetails: any;
arrayWithValues: Array<any>;
copy: any;
initQuot() {
this.service.checkExistQuot().subscribe(res => {
this.quotArray = res;
this.quotDetails = res.quotation.quotationdetail;
this.arrayWithValues = new Array<any>(['longueur','quantity']);
this.quotDetails.forEach((myArray, index) => {
for (var i = 0; i < this.arrayWithValues.length; i++) {
console.log(this.quotDetails)
this.arrayWithValues[i].longueur = myArray.longueur;
}console.log(this.arrayWithValues)
})
})
}
If anyone can help me find the answer and explain what I'm doing wrong there I would really appreciate it, thank you in advance !
You can use Array.map() and Object Destructuring for your purpose
this.arrayWithValues=this.quotDetails.map( ({ longueur,quantity }) => ({ longueur,quantity }))
Example:
let quotDetails=[
{
longeur:1,
quantity:1,
id:1,
quotationId:49,
totalFurniture:"123"
},
{
longeur:3,
quantity:5,
id:2,
quotationId:47,
totalFurniture:"323"
},
{
longeur:5,
quantity:0,
id:3,
quotationId:48,
totalFurniture:"23"
}
]
console.log(quotDetails.map( ({longeur,quantity})=> ({longeur,quantity})))
.as-console-wrapper { max-height: 100% !important; top: 0; }

Typescript - Querying or flattening nested array but keeping some objects as nested ones

Again I'm stuck with a nested Array of objects. I want to flatten it out, but I do have to keep some nested objects. The Problem I'm running into: How to rename the keys of the nested objects since I have an undefined number of nested objects. There might be 3 of them oder 8. So property1_3 has to be renamed to eg property1_3_1, property1_3_2 - depending on how many objects are in the original json data. And how to aply them to the correct parent object.
The json data I recieve looks like:
data = [{
"property1_1": "value1_1",
"property1_2": "value1_2",
"property1_3": [
[{
"subproperty1_1_1": "subvalue1_1_1",
"subproperty1_1_2": "subvalue1_1_2"
}],
[{
"subproperty1_2_1": "subvalue1_2_1",
"subproperty1_2_2": "subvalue1_2_2"
}]
]
},
{
"property2_1": "value2_1",
"property2_2": "value2_2",
"property2_3": [
[{
"subproperty2_1_1": "subvalue2_2_1",
"subproperty2_1_2": "subvalue2_2_2"
}],
[{
"subproperty2_2_1": "subvalue2_2_1",
"subproperty2_2_2": "subvalue2_2_2"
}],
[{
"subproperty2_3_1": "subvalue2_2_1",
"subproperty2_3_2": "subvalue2_2_2"
}]
]
}
]
What I want to achieve now is:
data = [
{
"property1_1": "value1_1",
"property1_2": "value1_2",
"property1_3_index1": {"subproperty1_1_1":"subvalue1_1_1", "subproperty1_1_2":"subvalue1_1_2"},
"property1_3_index2": {"subproperty1_2_1":"subvalue1_2_1", "subproperty1_2_2":"subvalue1_2_2"}
},
{
"property2_1": "value2_1",
"property2_2": "value2_2",
"property2_3_index1": {"subproperty2_1_1":"subvalue2_2_1", "subproperty2_1_2":"subvalue2_2_2"},
"property2_3_index2": {"subproperty2_2_1":"subvalue2_2_1", "subproperty2_2_2":"subvalue2_2_2"},
"property2_3_index3": {"subproperty2_3_1":"subvalue2_2_1", "subproperty2_3_2":"subvalue2_2_2"}
}
]
My last try was:
transformData(input) {
const testArray = [];
input.map(obj => {
for (const prop in obj) {
if (obj.hasOwnProperty(prop) && Array.isArray(obj[prop])) {
for (const [index, element] of obj[prop].entries()) {
testArray.push(element[0]);
}
}
}
});
}
but this only leeds to an array with all the single subobjects in one array. I'm also not quite sure if it's best trying to convert the original data or to build a new array as I tried before.
I finally found a way to achieve this.
transformData(input) {
return input.map(obj => {
for (const prop in obj) {
if (obj.hasOwnProperty(prop) && Array.isArray(obj[prop])) {
for (let i = 0; i < obj[prop].length; i++) {
const name = prop + (i + 1).toString();
obj[name] = obj[prop].flat(1)[i];
}
delete obj[prop];
}
}
return obj;
});
}

cookie in React JS (save/load)

I am new to using cookies in React JS and I have a question regarding my code below.
console.log(this.state.datasets);
cookie.save('datasets', this.state.datasets, { path: '/' , 'maxAge': 100000});
var myArray = cookie.load('datasets')
console.log(myArray);
this.state.datasets is an array full of elements and went I initially print the array to the console, I am able to see the data.
However when I try printing out myArray I get an empty array. Any idea what could be going wrong?
You can save only strings as cookies. To save an array you'll have to somehow convert it into a string. If you have an array of objects you can store it by converting it into string by JSON.stringify.
For example
let colors = [
{
color: "red",
value: "#f00"
},
{
color: "green",
value: "#0f0"
},
{
color: "blue",
value: "#00f"
}]
let x = JSON.stringify(colors)
The value x will be a string which you can save to cookies.
And to retrieve it you can convert it back to an array of objects by using JSON.parse.
Something like
var myArray = cookie.load('datasets')
let obj = JSON.parse(myArray)
obj will be the original object

Reading JSON into arrays in Angular (HttpClient)

i am trying to read JSON into different arrays using HttpClient for the use in Echarts, but since i am a newbie i couldn't find how to fill JSON into the different arrays.
the part code i used so far was:
....
label: Array<any>;
data: Array<any>;
tooltip: Array<any>;
constructor(private http: HttpClient) {
this.getJSON().subscribe(data => {
this.data=data.data;
this.label=data.label;
this.tooltip=data.tooltip;
console.log(data)
});
}
public getJSON(): Observable<any> {
return this.http.get("./assets/JSONData/TeamProgress.json")
}
the JSON file is formatted like this:
[{"label":"0","data":"0","tooltip":"0"},
{"label":"1","data":"-1","tooltip":" tooltip1"},
{"label":"2","data":"-1","tooltip":" tooltip2"},
...etc
i want to be able to get all labels of JSON in one array, and all data in another array, and all tooltips in a third array.
it would be great if you can help me.
thanks
First the result of that file should be a valid JSON structure aka (an object with key-values) you can group the array under a key called per example result
{
"result": [
{"label":"0","data":"0","tooltip":"0"},
{"label":"1","data":"-1","tooltip":" tooltip1"},
{"label":"2","data":"-1","tooltip":" tooltip2"},
//....Etc
]
}
Then you can access the data and filter it using map as below:
this.getJSON().subscribe((data:any) => {
this.label = data.result.map(element =>
// if you want to return an array of objects
{return {"label": element.label}}
// or if you want to return the raw values in an array, just do
element.label
});
this.data = data.result.map(element => {
return {"data": element.data}
});
this.tooltip = data.result.map(element => {
return {"tooltip": element.tooltip}
})
})

Resources