Specific data in chart - javascript

I'm getting this data from backend and need paste it in my Apex Charts chart - https://apexcharts.com/javascript-chart-demos/area-charts/spline/
{
"ADA": {
"name": "ADA",
"data": [
0,
0,
"98"
]
},
"MATIC": {
"name": "MATIC",
"data": [
"127",
"128",
"65"
]
},
"DOT": {
"name": "DOT",
"data": [
0,
"6",
"6"
]
}
}
Config looks like this with my stupid non iterate solution that works (series it's common array, inside objects with name/data)
series: [
{
name: props.portfolioGrowthData.data.chart_tokens_data.MATIC.name,
data: props.portfolioGrowthData.data.chart_tokens_data.MATIC.data.map(
(x, index) => x
),
},
{
name: props.portfolioGrowthData.data.chart_tokens_data.ADA.name,
data: props.portfolioGrowthData.data.chart_tokens_data.ADA.data.map(
(x, index) => x
),
},
{
name: props.portfolioGrowthData.data.chart_tokens_data.DOT.name,
data: props.portfolioGrowthData.data.chart_tokens_data.DOT.data.map(
(x, index) => x
),
},
],
But this solution it's not what i need because empty tokens displays in chart too and after scale of our app there gonna be a mess of tokens. Looks like i need somehow handle data from backend and iterate objects without static name and data but all my tries are failed... How can i handle it?

Related

TypeError: Cannot read properties of undefined (reading 'product-1')

So I am trying to display JSON data in my React.js project, but I am getting an error that I can't figure out. I've spent 2 days trying to figure it out, but had no luck
The JSON data: (filename: products.json)
{
"product-1": [
{
"id": 1,
"name": "product-1",
}
],
"product-2": [
{
"id": 2,
"name": "product-2",
}
],
"product-3": [
{
"id": 3,
"name": "product-3",
}
]
}
My javascript:
const productsData = Object.keys(backendData).map(key => {
return {
[key]: backendData[key]
}
})
console.log(productsData[0].products["product-1"][0].id)
error:
Log of backEndData:
Because productsData will return you array like this:
[
{ "product-1": [
{
"id": 1,
"name": "product-1",
}
]},
{"product-2": [
{
"id": 2,
"name": "product-2",
}
]}, ....
]
Meaning this is array of objects, where each object have one key-value pair, where key is name and value is an array.
If you want to access id then you should do like this:
productsData[0]["product-1"][0].id
UPDATED AFTER UPDATE OF OP
Since your backendData value does not match product.json, I will ignore that product.json and write you the solution which will work for the value of backendData you just provided.
const productsData = backendData.products;
const id = productsData[0]["product-1"][0].id;

Problem mapping over data from API as its just an object not an array of objects in React

If I have this data structure coming from an api:
{
"value": 0,
"time": [
"2021-10-15"
],
"innerArray": [
{
"name": "string",
"Value": [
0
]
}
]
}
I am trying to access the element by:
let dataLoop = data // object from api
then I am doing:
function Loop() {
dataLoop.map((inner: any) => {
console.log('series =', inner.innerArray);
})
};
But I am getting TypeError: dataLoop.map is not a function
It is because
{
"value": 0,
"time": [
"2021-10-15"
],
"innerArray": [
{
"name": "string",
"Value": [
0
]
}
]
}
is an object, you can map only on Array type elements.
innerArray is an element on which you can .map like this:
dataLoop.innerArray.map((inner: any) => {
console.log('series =', inner);
})
to be able to map through an object you have to use Object like:
Object.entries(data).map(([key,value])=>{
console.log(key,value)
})
for example, so output would be like :

how to make nested array objects in javascript in a key value pair format

array data=[
{
"id":1,
"name":"john",
"income":22000,
"expenses":15000
},
{
"id":2,
"name":"kiran",
"income":27000,
"expenses":13000
},
{
"id":1,
"name":"john",
"income":35000,
"expenses":24000
}
]
i want to make a new array set in following format which is in a key value pair. ie result set.
can you please explain the best method. ? how to achive using foreach.?
tried using foreach method by looping each element. but cant get the desired output format
var result= [ {
"name": "john",
"series": [
{
"name": "income",
"value": 22000
},
{
"name": "expenses",
"value": 15000
},
]
},
{
"name": "kiran",
"series": [
{
"name": "income",
"value": 27000
},
{
"name": "expenses",
"value": 13000
},
]
}]
// Your array
const result = [
{
name: "john",
series: [
{
name: "income",
value: 22000,
},
{
name: "expenses",
value: 15000,
},
],
},
{
name: "kiran",
series: [
{
name: "income",
value: 27000,
},
{
name: "expenses",
value: 13000,
},
],
},
];
// What is .map function?
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
// Output
// map return a new function.
// it's a loop method but more equipped
result.map((item, index) => {
const seriesKeyValues = {};
// forEach is too, it's a loop method.
// but not have a return value,
// just loops and give you item on each loop
item.series.forEach(serie => {
//seriesKeyValues is a object.
// different between seriesKeyValues.serie.name
// it's a bracket notation
// look this documentation
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#computed_property_names
seriesKeyValues[serie.name] = serie.value;
});
// return new Object
// ... is 'spread syntax' basically combine objects
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#spread_properties
// spread syntax is a new way.
// old way is https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
return {
id: index,
name: item.name,
...seriesKeyValues,
};
});
I hope it will help :). if you don't understand any lines of code, i can explain

Modify object while passing through react component

I am trying to pass through an object that looks like this
{
"nodes": [
{
"attributes": null
},
{
"attributes": {
"nodes": [
{
"attributeId": 1,
"name": "pa_color",
"options": [
"gray"
]
},
{
"attributeId": 2,
"name": "pa_size",
"options": [
"large"
]
}
]
}
},
{
"attributes": {
"nodes": [
{
"attributeId": 1,
"name": "pa_color",
"options": [
"blue"
]
}
]
}
}
]
}
into a react component that renders all the different options under all the unique names. However, the way the data is structured means that I receive duplicates of names and options.
I am trying to convert the object into this object
{
"node": {
"attributeId": 1,
"name": "pa_color",
"values": [
{
"name": "gray"
},
{
"name": "blue"
}
]
},
"node": {
"attributeId": 2,
"name": "pa_size",
"values": [
{
"name": "large"
}
]
},
}
Current code looks like this
export interface Category_products_edges_node_attributes_edges_node {
__typename: "ProductAttribute";
/**
* Attribute Global ID
*/
name: string;
/**
* Attribute options
*/
options: (string | null)[] | null;
/**
* Attribute ID
*/
attributeId: number;
}
export interface ProductFiltersProps {
attributes: Category_products_edges_node_attributes_edges_node[]
}
export const ProductFilters: React.FC<ProductFiltersProps> = ({
attributes,
}) => (
<div className="product-filters">
<div className="container">
<div className="product-filters__grid">
{attributes.map(attribute => (
I have tried to do
{groupBy(attributes, 'attributeId').map(attribute => (
With the Lodash library, but receive the error
This expression is not callable. Type
'Category_products_edges_node_attributes_edges_node[]' has no call
signatures.
What is the best way to do this?
Thank you
lodash groupBy returns an Object not an Array therefore the javascript .map call will not work on it. Also groupBy is used to group items with similar property under one key inside an object, it isn't used to remove duplicates.
To remove duplicates use the lodash uniqBy method. This method can be called on an array and returns an array without duplicates.
Update:
To view in more detail how you can remove duplicates based on more than one property of object please see great answer
Also the output object you are trying to achieve has similar keys, I think that is not what you want, a Javascript object should not have duplicate keys. So my output gives keys as node0, node1 instead of node
You can achieve this as follows:
const nodes = {
nodes: [
{ attributes: null },
{
attributes: {
nodes: [
{ attributeId: 1, name: "pa_color", options: ["gray"] },
{ attributeId: 2, name: "pa_size", options: ["large"] }
]
}
},
{
attributes: {
nodes: [{ attributeId: 1, name: "pa_color", options: ["blue"] }]
}
}
]
}
const attributes = []
nodes.nodes.forEach(e => {
if (e.attributes && Array.isArray(e.attributes.nodes)) {
attributes.push(...e.attributes.nodes)
}
})
const uniqueAttributes = _.uniqBy(attributes, (obj) => [obj.attributeId, obj.name, obj.options].join())
const uniqueNodes = uniqueAttributes.map((e, i) => ({ ["node" + i]: e }))
console.log("Unique Nodes: ", uniqueNodes)
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.10/lodash.min.js"></script>

how to loop through objects and change the property keys in a data set

I have a set of data that needs to be reformatted according to a specific format that i desire.
Below is the format of data that I'm receiving.
const recieved = [
{
"name": "1PM Industries IncĀ ",
"series": [
{
"value": 0.0001,
"name": "2019-08-30"
},
{
"value": 0,
"name": "2019-08-28"
}
]
}
]
What i need to do is iterate through all object property keys "name", "series", "value" and change them to "id", "data" , "x" and "y" respectively.
Below is the format of data that i want the above data set to be changed.
I need the "name" to be replaced with "x" and "value" should be replaced with "y"
const columns = [
{
"id": "japan",
"data": [
{
"x": "plane",
"y": 45
},
{
"x": "helicopter",
"y": 253
}
]
}
]
I found out that we can access property keys of objects by Object.keys
function formatData(columns) {
columns.map(col => {
})
}
I find myself in really hard situations when it comes to formatting of data. Hope someone could help me with this. Thanks
This should work:
received.map(r => ({
id: r.name,
data: r.series.map(s => ({
x: s.name,
y: s.value
}))
}));
Map over each received object, return a new object. id of the new object is name of the received object. data of new object is a map of series of old objects converting name to x and value to y.
You could rename the properties (Assigning to new variable names) and generate new objects.
const
recieved = [{ name: "1PM Industries Inc ", series: [{ value: 0.0001, name: "2019-08-30" }, { value: 0, name: "2019-08-28" }] }],
result = recieved.map(({ name: id, series }) => ({
id,
data: series.map(({ value: x, name: y }) => ({ x, y }))
}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can use map method for this.
const recieved = [
{
"name": "1PM Industries Inc ",
"series": [
{
"value": 0.0001,
"name": "2019-08-30"
},
{
"value": 0,
"name": "2019-08-28"
}
]
}
]
let output = recieved.map(o=>{
let data = o.series.map((i)=>{ return {x: i.value, y: i.name}});
return {id: o.name, data}
});
console.log(output)
you can use for..in loop in conjunction with hasOwnProperty() method
use recursion to have a better script

Categories

Resources