How to create a combination of array is react js? - arrays

I need to create a combination of arrays.
I have the data like this and I need to arrange the data for the chart series
[
{
"movingDuration":10,
"parkedDuration":15,
},
{
"movingDuration":15,
"parkedDuration":23,
},
{
"movingDuration":43,
"parkedDuration":26,
},
{
"movingDuration":67,
"parkedDuration":21,
},
{
"movingDuration":47,
"parkedDuration":54,
}
]
and I expected a result like this the following method
[
{
"name":"Moving Duration",
"data":[
10,
15,
43,
67,
47
]
},
{
"name":"Parked Duration",
"data":[
15,
23,
26,
21,
54
]
}
]
Any help would be appreciated. thank you

Run the data through an array reduce to group by property key, then map it to the resultant object format you want.
const formattedData = data.reduce((data, current) => {
Object.entries(current).forEach(([key, value]) => {
data[key] = [...(data[key] ?? []), value];
});
return data;
}, {});
const finalData = Object.entries(formattedData).map(([name, data]) => ({
name,
data
}));
const data = [
{
movingDuration: 10,
parkedDuration: 15
},
{
movingDuration: 15,
parkedDuration: 23
},
{
movingDuration: 43,
parkedDuration: 26
},
{
movingDuration: 67,
parkedDuration: 21
},
{
movingDuration: 47,
parkedDuration: 54
}
];
const formattedData = data.reduce((data, current) => {
Object.entries(current).forEach(([key, value]) => {
data[key] = [...(data[key] ?? []), value];
});
return data;
}, {});
const finalData = Object.entries(formattedData).map(([name, data]) => ({
name,
data
}));
console.log(finalData);

Does this help?
const arr = [
{
movingDuration: 10,
parkedDuration: 15
},
{
movingDuration: 15,
parkedDuration: 23
},
{
movingDuration: 43,
parkedDuration: 26
},
{
movingDuration: 67,
parkedDuration: 21
},
{
movingDuration: 47,
parkedDuration: 54
}
];
const resultArray = [{ name: 'Moving Duration', data: [] }, { name: 'Parked Duration', data: [] }];
arr.forEach((ele) => {
resultArray[0].data.push(ele.movingDuration);
resultArray[1].data.push(ele.parkedDuration);
});

Let me know if this helps.
const origData=[
{
"movingDuration":10,
"parkedDuration":15,
},
{
"movingDuration":15,
"parkedDuration":23,
},
{
"movingDuration":43,
"parkedDuration":26,
},
{
"movingDuration":67,
"parkedDuration":21,
},
{
"movingDuration":47,
"parkedDuration":54,
}
]
const cols=Object.keys(origData[0])
const result=cols.map(item=>{
const data=origData.map(i=>i[item])
return {name:item,data}
})
console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }

let data = [
{
"movingDuration":10,
"parkedDuration":15,
},
{
"movingDuration":15,
"parkedDuration":23,
},
{
"movingDuration":43,
"parkedDuration":26,
},
{
"movingDuration":67,
"parkedDuration":21,
},
{
"movingDuration":47,
"parkedDuration":54,
}
]
let sol = {}
data.forEach(d => {
let keys = Object.keys(d);
if(sol[keys[0]]){
sol[keys[0]] = [...sol[keys[0]], d[keys[0]]]
sol[keys[1]] = [...sol[keys[1]], d[keys[1]]]
}else{
sol[keys[0]] = [].concat(d[keys[0]])
sol[keys[1]] = [].concat(d[keys[1]])
}
})
let final = Object.keys(sol).map(key =>{
let temp = {}
temp["name"] = key
temp["data"] = sol[key]
return temp
})
console.log(final)

We can use reduce() method to create an object with Object.values() to get values from object:
const result = data.reduce((a, c) => {
for (const key in c) {
a[key] = a[key] || {name: key, data: []};
a[key].data.push(c[key]);
}
return a;
}, {})
console.log(Object.values(result));
An example:
let data = [
{
"movingDuration":10,
"parkedDuration":15,
},
{
"movingDuration":15,
"parkedDuration":23,
},
{
"movingDuration":43,
"parkedDuration":26,
},
{
"movingDuration":67,
"parkedDuration":21,
},
{
"movingDuration":47,
"parkedDuration":54,
}
]
const result = data.reduce((a, c) => {
for (const key in c) {
a[key] = a[key] || {name: key, data: []};
a[key].data.push(c[key]);
}
return a;
}, {})
console.log(Object.values(result));

Related

Why can't I push in <option> when I get the 'response.data'?

Why can't I push in my <option> when I get the response.data?
type State = {
companyManagerMap: null | Map<string, string[]>
}
useEffect(() => {
AdminListManager()
.then((response) => {
const { data } = response.data
console.log( { data });
setState((s) => ({
...s,
companyManagerMap: new Map(
Object.keys(data).map((key) => [key, data[key]])
),
}))
})
.catch(showUnexpectedError)
}, [showUnexpectedError])
data format
{"total":2,"data":[{"id":1,"name":"newspeed","contains_fields":[{"id":1,"name":"Official"}]},{"id":2,"name":"YAMAHA","contains_fields":[{"id":3,"name":"US"}]}]}
You are using your .map and Object.keys wrong
Look here at where you iterate over your Object keys properly :)
const data = {
total: 2,
data: [
{ id: 1, name: 'newspeed', contains_fields: [{ id: 1, name: 'Official' }] },
{ id: 2, name: 'YAMAHA', contains_fields: [{ id: 3, name: 'US' }] },
],
};
//now iterate over it properly
data.data.map((item) => {
Object.keys(item).map((key) => {
console.log(item[key]);
});
});
console.log will return this output
1
newspeed
[ { id: 1, name: 'Official' } ]
2
YAMAHA
[ { id: 3, name: 'US' } ]
I'm guessing you want to add the new data from your res.data to a state
So you can do something like this:
const fetchData = async () => {
try {
const res = await AdminListManager()
//do data manipulation over objects and set new state
} catch (error) {
showUnexpectedError()
}
}
useEffect(()=> {
fetchData()
}, [showUnexpectedError])

Remove object in array

I have a array object and a array.
const arr1=[
{ name: "viet" },
{ name: "hai" },
{ name: "han" }
]
const arr2= ["viet", "hai"];
How can i compare and set arr like:
arr = [{name: "han"}]
Try this code :D
const arr1=[
{ name: "viet" },
{ name: "hai" },
{ name: "han" }
]
const arr2= ["viet", "hai"];
const result = arr1.filter(item => !arr2.includes(item.name))
console.log(result) // [{name: "han"}]
const arr1=[
{ name: "viet" },
{ name: "hai" },
{ name: "han" }
]
const arr2= ["viet", "hai"];
let res = arr1.filter(function (n) {
return !this.has(n.name);
}, new Set(arr2));
console.log(res);

Adding object in Array in nested object with setState

I'd like to know how to add an object in datasets,
I'm trying to add an object in array with using setState,
but It doesn't work at all .
my code is like this :
const [DataContext, setDataContext] = useState([
{
labels: defaultLabels,
datasets: [
{
label: "dataSetting",
data: defaultDatas,
backgroundColor: defaultBackgroundColor,
},
],
},
{
labels: defaultLabels,
datasets: [
{
label: "dataSetting",
data: defaultDatas,
backgroundColor: defaultBackgroundColor,
},
],
},
{
labels: defaultLabels,
datasets: [
{
label: "dataSetting",
data: defaultDatas,
backgroundColor: defaultBackgroundColor,
},
],
},
const addAxis = index => {
let addAxis = [...DataContext];
addAxis[index].datasets.push({ label: "", data: "", background: "" });
setDataContext(addAxis);
};
You need a deep copy to update the state:
const addAxis = index => {
setDataContext(dataContext => dataContext.map((data, idx) => {
return idx === index ? {
...data,
datasets: [...data.datasets, { label: "", data: "", background: "" }]
} : data
})
};
You need to deep copy DataContext.
const _copy = (value) => {
let object;
if (Array.isArray(value)) {
object = [];
value.forEach((item, index) => {
if (typeof value[index] === 'object') {
object[index] = _copy(value[index]);
} else {
object[index] = value[index];
}
});
} else {
object = {};
for (let key in value) {
if (typeof value[key] === 'object') {
object[key] = _copy(value[key]);
} else {
object[key] = value[key];
}
}
}
return object;
};
const addAxis = index => {
let addAxis = _copy(DataContext);
addAxis[index].datasets.push({ label: "", data: "", background: "" });
setDataContext(addAxis);
};

Update objects in an array inside map Function React or React-Hooks or React-Native

it is deleting all objects except last one from the array instead of updating a property of all objects, want to update 'ItemDeliveryStatus' of all objects inside map function
const [arrayList, setArrayList] = useState([
{ Id: 1, Name:'A', ItemDeliveryStatus:1 },
{ Id: 2, Name:'B', ItemDeliveryStatus:1 },
{ Id: 3, Name:'C', ItemDeliveryStatus:1 },
{ Id: 4, Name:'D', ItemDeliveryStatus:1 },
])
const [returnCount, setReturnCount ]=useState(0)
const updateAllObjects=()=>
{
arrayList.map(items=>
{
if(items.ItemDeliveryStatus==1)
{
setArrayList([{ ...items, ItemDeliveryStatus:4}])
}
if (items.ItemDeliveryStatus==4)
{
setReturnCount(prev=>prev+1)
}
})
}
final Result Should be like this
([
{ Id: 1, Name:'A', ItemDeliveryStatus:4 },
{ Id: 2, Name:'B', ItemDeliveryStatus:4 },
{ Id: 3, Name:'C', ItemDeliveryStatus:4 },
{ Id: 4, Name:'D', ItemDeliveryStatus:4 },
])
You can update like this for all object:
const updateAllObjects = (value) => {
setArrayList(
arrayList.map((item) => {
if (item.ItemDeliveryStatus == 1) {
return { ...item, ItemDeliveryStatus: value };
};
return item;
})
);
};

React API Call, can't assign to pass as props to other components

I wanted to see if I could get some help on HOW to call data points in this api call, it is an array of numbers, so a field value might be 6. But I can't ever get anything to load on screen. My call is working as I'm getting the Loading... when null, but then it just disappears and doesn't display anything. Whenever I try to assign a Number to data, it says unrecognized.
import React, { Component } from 'react'
let headers = {
'QB-Realm-Hostname': 'XXXXXXXXXXXXXX.quickbase.com',
'User-Agent': 'FileService_Integration_V2.1',
'Authorization': 'QB-USER-TOKEN XXX_XXXX_XXXXXXXXXXXXXXXXXXX',
'Content-Type': 'application/json'
};
class JobsTableApi extends Component {
state = {
data: null,
}
componentDidMount() {
this.fetchData();
}
fetchData = () => {
let body = {"from":"bpz99ram7","select":[3,6,80,81,82,83,86,84,88,89,90,91,92,93,94,95,96,97,98,99,101,103,104,105,106,107,109,111,113,115,120,123,224,225,226,227,228,229,230,231,477,479,480,481],"sortBy":[{"fieldId":6,"order":"ASC"}],"groupBy":[{"fieldId":40,"grouping":"equal-values"}],"options":{"skip":0,"top":0,"compareWithAppLocalTime":false}}
fetch('https://api.quickbase.com/v1/records/query', {
method: 'POST',
headers: headers,
body: JSON.stringify(body)
}).then(response => {
if (response.ok) {
return response.json().then(res => {
this.setState({
data: [],
})
});
}
return response.json().then(resBody => Promise.reject({status: response.status, ...resBody}));
}).catch(err => console.log(err))
}
render() {
const { data } = this.state;
if (data === null) return 'Loading...';
return (
<div>{data["3"]}</div>
)
}
}
export default JobsTableApi;
API data Ex:
{
"data": [
{
"3": {
"value": 43
},
"18": {
"value": "Radiant"
},
"20": {
"value": null
},
"144": {
"value": null
},
"145": {
"value": 33230
},
"171": {
"value": 8
},
"172": {
"value": 228
},
"174": {
"value": 270
},
"212": {
"value": 0
},
"215": {
"value": 8.34487776140499
},
"216": {
"value": 16.34487776140499
},
"217": {
"value": 244.344877761405
},
"218": {
"value": 572.3449342166289
},
"219": {
"value": 842.3449342166289
},
"220": {
"value": 861.8163156599072
},
"221": {
"value": 877.8106647026001
},
"222": {
"value": 0
},
"223": {
"value": 239.256
},
"227": {
"value": 5050.96
},
"230": {
"value": 239.256
},
"231": {
"value": 239.256
},
"232": {
"value": 17339.414
},
"233": {
"value": 26743.504
},
"234": {
"value": 22390.374
},
"235": {
"value": 22948.638
},
"236": {
"value": 23407.212
},
"244": {
"value": 0
},
"249": {
"value": 0
},
"322": {
"value": 870.6260000000001
},
"325": {
"value": 17100.158
},
"338": {
"value": ""
},
"349": {
"value": 8
},
"350": {
"value": 0
},
"351": {
"value": 220
},
"366": {
"value": 0
},
"438": {
"value": null
},
"513": {
"value": 278
},
"516": {
"value": 23261
},
"517": {
"value": 17339.414
}
}
UPDATE: Able to set the {jobId} as a prop in my App.js, since this is the parent to my Line Charts, this is where the truth needs to be, then I can send this over to each line chart to pull based on which Title (and therefore ID) is displaying which dictates the result of the API call.
App.js
import React, { useEffect, useState } from "react";
import './App.css'
import Title from './components/header/Title'
import TotalLineChart from './components/charts/TotalLineChart'
import RadiantLineChart from './components/charts/RadiantLineChart'
import PlumbingLineChart from './components/charts/PlumbingLineChart'
import SnowmeltLineChart from './components/charts/SnowmeltLineChart'
import HVACLineChart from './components/charts/HVACLineChart'
import GasPipeLineChart from './components/charts/GasPipeLineChart'
import FixturesLineChart from './components/charts/FixturesLineChart'
// import TitleCycle from './components/TitleCycle'
// import Logo from './components/Logo';
let headers = {
"QB-Realm-Hostname": "XXXXXX.quickbase.com",
"User-Agent": "FileService_Integration_V2.1",
"Authorization": "QB-USER-TOKEN XXXXXXX",
"Content-Type": "application/json",
"Retry-After": 120000
};
function App() {
const [allData, setAllData] = useState([]);
const [index, setIndex] = useState(0);
// Fetch all data, all jobs
useEffect(() => {
function fetchData() {
let body = {
from: "bpz99ram7",
select: [3, 6, 40],
where: "{40.CT. 'In Progress'}",
sortBy: [{ fieldId: 6, order: "ASC" }],
groupBy: [{ fieldId: 40, grouping: "equal-values" }],
options: { skip: 0, top: 0, compareWithAppLocalTime: false },
};
fetch("https://api.quickbase.com/v1/records/query", {
method: "POST",
headers: headers,
body: JSON.stringify(body),
})
.then((response) => response.json())
.then(({ data }) => setAllData(data));
}
fetchData();
}, []);
// Cycle through the jobIds and indexes
useEffect(() => {
const timerId = setInterval(
() => setIndex((i) => (i + 1) % allData.length),
5000 // 5 seconds.
);
return () => clearInterval(timerId);
}, [allData]);
// console.log(allData)
// console.log(index)
// Calculate info based on index
const jobId = allData[index]?.['3']?.value || '291'; // Default 291
const title = allData[index]?.['6']?.value || 'Default Title';
// console.log(jobId)
return (
<div>
{/* <div className="flexbox-container">
<div className="Logo">
{/* <Logo /> */}
{/* </div> */}
<div className="App">
<Title title = {title} />
</div>
<div className="TopChart">
<TotalLineChart jobId = {jobId} />
</div>
<div className="FirstRowContainer">
{/* <RadiantLineChart jobId = {jobId} /> */}
<PlumbingLineChart jobId = {jobId} />
<FixturesLineChart jobId = {jobId} />
</div>
<div className="SecondRowContainer">
<SnowmeltLineChart jobId = {jobId} />
<HVACLineChart jobId = {jobId} />
<GasPipeLineChart jobId = {jobId} />
</div>
</div>
);
}
export default App;
LineChart.js
import React, { useState, useEffect } from "react";
import { Scatter } from "react-chartjs-2";
// import jobId from '../TitleCycle';
// import Title from '../header/Title';
function TotalLineChart(props) {
const { jobId } = props;
// console.log(`${jobId}`)
const [chartData, setChartData] = useState({});
const chart = () => {
let designHours = [];
let designAmount = [];
let subRoughHours = [];
let subRoughAmount = [];
let roughHours = [];
let roughAmount = [];
let finishHours = [];
let finishAmount = [];
let closeHours = [];
let closeAmount = [];
let actualHours = [];
let actualAmount = [];
let headers = {
"QB-Realm-Hostname": "XXXXXXXXXX.quickbase.com",
"User-Agent": "FileService_Integration_V2.1",
"Authorization": "QB-USER-TOKEN XXXXXXXXXXX",
"Content-Type": "application/json",
"x-ratelimit-reset": 10000,
"Retry-After": 30000
};
// useEffect(() => {
// function fetchData() {
const body = {
from: "bpz99ram7",
select: [
3,
88,
91,
92,
95,
96,
98,
104,
107,
224,
477,
479,
480,
],
where: `{3.EX. ${ jobId }}`,
sortBy: [{ fieldId: 6, order: "ASC" }],
groupBy: [{ fieldId: 40, grouping: "equal-values" }],
options: { skip: 0, compareWithAppLocalTime: false }
};
fetch("https://api.quickbase.com/v1/records/query", {
method: "POST",
headers: headers,
body: JSON.stringify(body)
})
// }
// fetchData();
// }, [])
.then((response) => response.json())
.then((res) => {
// console.log(res);
Object.keys(res.data).map(jobId => {
designHours = parseInt(res.data[jobId]['88'].value, 10);
designAmount = parseInt(res.data[jobId]['91'].value, 10);
subRoughHours = parseInt(res.data[jobId]['92'].value, 10);
subRoughAmount = parseInt(res.data[jobId]['95'].value, 10);
roughHours = parseInt(res.data[jobId]['96'].value, 10);
roughAmount = parseInt(res.data[jobId]['98'].value, 10);
finishHours = parseInt(res.data[jobId]['104'].value, 10);
finishAmount = parseInt(res.data[jobId]['107'].value, 10);
closeHours = parseInt(res.data[jobId]['477'].value, 10);
closeAmount = parseInt(res.data[jobId]['480'].value, 10);
actualHours = parseInt(res.data[jobId]['479'].value, 10);
actualAmount = parseInt(res.data[jobId]['224'].value, 10);
setChartData({
type: 'scatter',
redraw: true,
datasets: [
{
label: 'TOTAL',
data: [
{ x: designHours, y: designAmount },
{ x: subRoughHours, y: subRoughAmount },
{ x: roughHours, y: roughAmount },
{ x: finishHours, y: finishAmount },
{ x: closeHours, y: closeAmount }
],
borderWidth: 2,
borderColor: '#4183c4',
backgroundColor: '#4183c4',
tension: 0.8,
spanGaps: true,
lineTension: 0.5,
showLine: true,
fill: false,
showTooltip: false,
pointBorderWidth: 1
},
{
label: 'ACTUALS',
data: [{ x: actualHours, y: actualAmount }],
fill: false,
borderColor: '#e34747',
backgroundColor: '#e34747',
borderWidth: 3,
showTooltip: false
}
],
options: {
showAllTooltips: true,
enabled: true,
maintainAspectRatio: false,
legend: {
display: true
}
}
})
})
})
.catch((err) => {
console.log(err);
});
};
useEffect(() => {
chart();
}, []);
return (
<div className="App">
<div>
<Scatter
// ref={(reference) => this.chartReference = reference }
data={chartData}
options={{
title: { text: "Total Project", display: false },
scales: {
yAxes: [
{
scaleLabel: {
display: true,
labelString: '$ AMOUNT'
},
ticks: {
autoSkip: true,
maxTicksLimit: 10,
beginAtZero: true
},
gridLines: {
display: true
}
}
],
xAxes: [
{
scaleLabel: {
display: true,
labelString: 'HOURS'
},
gridLines: {
display: true
}
}
],
},
}}
/>
</div>
</div>
);
};
export default TotalLineChart;
As you can see, the API is getting the '#' id of whatever {jobId} is coming from App.js. Which you can also see in my API body.

Resources