Creating highchart piechart with a javascript object - javascript

I am using highchart to create a graph. I have a javsascript object like this
test1:38
test2:2
test3:160
I want to create a piechart with the values of this object something like this
series: [{
name: 'Success',
data: [
{name:"test1", y:1},
{name:"test2", y:38},
{name:"test3", y:k},]
}]
How can I create the data array like this using my javascript object.I am new to javascript so any help would be appreciated.

You could map the entries of the object to get the data array
const input = {
test1: 38,
test2: 2,
test3: 160
}
const data = Object.entries(input)
.map(([name, y]) => ({ name, y }))
console.log(data)
const chart = {
series: [{
name: 'Success',
data
}]
}
console.log(chart)

Related

How can I extract and pair the values of an array based object

I'm trying to create a String based upon an object consisting of several key-value pairs.
Example:
[{ name: 'cookie1', value: 'false' },
{ name: 'cookie2', value: '123' },
{ name: 'cookie3',value: 'abc'}]
What I'm trying to achieve (string):
cookie1: false, cookie2: 123, cookie3: abc
I've tried to extract just the val using map like this (played around moving around values):
var output = cookies.map(d => {
return {
"name": d.name,
"value": d.value,
}
})
One way to do this is to map the array of objects into name: value strings and then join them with , :
const data = [{ name: 'cookie1', value: 'false' },
{ name: 'cookie2', value: '123' },
{ name: 'cookie3',value: 'abc'}]
const result = data.map(({ name, value }) => `${name}: ${value}`).join(', ')
console.log(result)

Update nested data arrays of object (Redux)

I have an issue with updating the immutable redux and quite nested data. Here's an example of my data structure and what I want to change. If anyone could show me the pattern of accessing this update using ES6 and spread operator I would be thankful. 😀
const formCanvasInit = {
id: guid(),
fieldRow: [{
id: guid(),
fieldGroup: [
{ type: 'text', inputFocused: true }, // I want to change inputFocused value
{ type: 'text', inputFocused: false },
],
}],
// ...
};
This should do the trick, assuming the data is set up exactly as shown, with the given array indices:
const newData = {
...formCanvasInit,
fieldRow: [{
...formCanvasInit.fieldRow[0],
fieldGroup: [
{ ...formCanvasInit.fieldRow[0].fieldGroup[0], inputFocused: newValue },
...formCanvasInit.fieldRow[0].fieldGroup.slice(1, formCanvasInit.fieldRow[0].fieldGroup.length)
]
}]
};
If index of the element to be changed is to be determined dynamically, you'll need to use functionality such as filter to find and remove the array element you're updating, and then spread the corresponding subarrays by editing the structure of the call to slice.
Try using Immutability Helper
I think in your structure, like this
let news = update(formCanvasInit, {
fieldRow: [{
fieldGroup: [
{ $set: {type: "number", inputFocused: false}}
]
}]
})
I've tried it
Click Me
This is a longer solution but might help you as your redux state grows. I've also changed some of the values in the original state to make a clearer explanation.
const formCanvasInit = {
id: 'AAAAXXXX',
fieldRow: [
{
id: 1001,
fieldGroup: [
{type: 'text1', inputFocused: true}, // I want to change inputFocused value
{type: 'text2', inputFocused: false},
]
},
{
id: 1002,
fieldGroup: [
{type: 'text3', inputFocused: true},
{type: 'text4', inputFocused: true},
]
}
]
};
// the id of the field row to update
const fieldRowID = 1001;
// the value of the field type to update
const fieldTypeValue = 'text1';
const fieldRow = [...formCanvasInit.fieldRow];
// obtain the correct fieldRow object
const targetFieldRowIndex = formCanvasInit.fieldRow.findIndex(fR => fR.id === fieldRowID);
let fieldRowObj = targetFieldRowIndex && formCanvasInit.fieldRow[targetFieldRowIndex];
// obtain that fieldRow object's fieldGroup
const fieldGroup = [...fieldRowObj.fieldGroup];
// obtain the correct object in fieldGroup
const fieldIndex = fieldGroup.findIndex(fG => fG.type === fieldTypeValue);
const fieldToChange = fieldIndex && fieldGroup[fieldIndex];
// replace the old object in selected fieldGroup with the updated one
fieldGroup.splice(fieldIndex, 1, {...fieldToChange, inputFocused: false});
// update the target fieldRow object
fieldRowObj = {...fieldRowObj, fieldGroup};
// replace the old fieldGroup in selected fieldRow with the updated one
fieldRow.splice(targetFieldRowIndex, 1, fieldRowObj);
// create the new formCanvasInit state
const newFormCanvasInit = {...formCanvasInit, fieldRow};

javascript merge arrays into a single object

I am trying to merge several arrays into a single object that I can then iterate to use in chart.js datasets. I have a set of data that looks like this:
export const data = [
{
'name': 'Flow',
'values': {
'sent': 410,
'responded': 253,
'secured': 65
}
}
]
(I limited this to just one, but the dataset is much larger)
Then I have several arrays that I've built based on this data:
this.labels = data.map(item => item.name);
this.colors = ['#439ff4', '#5ec3d5', '#a068e5'];
this.responded = data.map(item => item.values.responded);
this.sent = data.map(item => item.values.sent);
this.secured = data.map(item => item.values.secured);
What I need to do is this:
get the key names (responded, sent, secured) as another array
merge the keys, colors, responded, sent, and secured, arrays into an object called datasets.
this.datasets = [ /* not sure what to do here! */];
Ultimately my chart in chart js is looking for something like this (I have partially hard-coded values at the moment:
datasets: [
{
label: 'Sent',
data: this.sent,
backgroundColor: '#439ff4'
},
{
label: 'Responded',
data: this.responded,
backgroundColor: '#5ec3d5'
},
{
label: 'Secured',
data: this.secured,
backgroundColor: '#a068e5'
}
],
that I would ultimately like to just express as
datasets: this.datasets,
I hope I explained this well enough as to what I am trying to do.
Assuming that the key names in data.values stays in lowercase and otherwise it is same as datasets[*].label, you can do something like below.
// the custom type is just for making it more manageable, omit it if you want
type DatasetItem = { label: string, data: number[], backgroundColor: string };
let datasets: Array<Partial<DatasetItem>> = [
{
label: 'Sent',
backgroundColor: '#439ff4'
},
{
label: 'Responded',
backgroundColor: '#5ec3d5'
},
{
label: 'Secured',
backgroundColor: '#a068e5'
}
];
const data = [
{
'name': 'Flow1',
'values': {
'sent': 410,
'responded': 253,
'secured': 65
}
},
{
'name': 'Flow2',
'values': {
'sent': 411,
'responded': 254,
'secured': 66
}
}
];
datasets.forEach((item) => item.data = data.map((d) => d.values[item.label.toLowerCase()]));
console.log(datasets);

json object from javascript nested array

I'm using a nested array with the following structure:
arr[0]["id"] = "example0";
arr[0]["name"] = "name0";
arr[1]["id"] = "example1";
arr[1]["name"] = "name1";
arr[2]["id"] = "example2";
arr[2]["name"] = "name2";
now I'm trying to get a nested Json Object from this array
arr{
{
id: example0,
name: name00,
},
{
id: example1,
name: name01,
},
{
id: example2,
name: name02,
}
}
I tought it would work with JSON.stringify(arr); but it doesen't :(
I would be really happy for a solution.
Thank you!
If you are starting out with an array that looks like this, where each subarray's first element is the id and the second element is the name:
const array = [["example0", "name00"], ["example1", "name01"], ["example2", "name02"]]
You first need to map it to an array of Objects.
const arrayOfObjects = array.map((el) => ({
id: el[0],
name: el[1]
}))
Then you can call JSON.stringify(arrayOfObjects) to get the JSON.
You need to make a valid array:
arr = [
{
id: 'example0',
name: 'name00',
},
{
id: 'example1',
name: 'name01',
},
{
id: 'example2',
name: 'name02',
}
];
console.log(JSON.stringify(arr));
Note that I am assigning the array to a variable here. Also, I use [] to create an array where your original code had {}.

How to map model to table when the structure is array based?

I have my data as following:
{
meta: {
format: "csv",
info: "desc",
columns: [
{
id: "Name",
type: "Text",
length: 32
},
{
id: "Text",
type: "Text",
length: 128
}]
},
rows: [
["John","xxxx"],
["Alpha","yyyy"],
["Beta","wwww"],
["Gamma","zzzz"]]
}
Now, I am struggling to map the records to a Table control as Columns and Rows. Column seems straight forward, straight map, but the rows since lacks a mapping to column I wonder what could be the simplest way.
Approach Steps:
Make a keys[] from column.id of each columns record.
Traverse the rows[]
Each loop, while keys.length create an object as {keys[j]:row[k]}
Push to an array
Recreate the original JSON but replace Rows arrays with Objects
I am really struggling to translate this into code specially at the rows[] parsing and creating Objects. Is there, I am sure there must be, an efficient way to achieve this.
Here is what you could do. using Array.map and forEach.
var input = {
meta: {
format: "csv",
info: "desc",
columns: [{
id: "Name",
type: "Text",
length: 32
}, {
id: "Text",
type: "Text",
length: 128
}]
},
rows: [
["John", "xxxx"],
["Alpha", "yyyy"],
["Beta", "wwww"],
["Gamma", "zzzz"]
]
};
var columns = input.meta.columns.map((column) => {
return column.id
});
var rows = input.rows.map((row) => {
var obj = {};
row.forEach((column, idx) => {
obj[columns[idx]] = column;
});
return obj;
});
input.rows = rows;
console.log(input);

Categories

Resources