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

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

Related

Specific data in chart

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?

How to update object based off objects specific value?

I have 2 objects and I want to 'transplant' values from one object into the other.
The first object I am drawing data from looks like:
var userData = {
Data: [
{
Amount: 430140.68,
Year: "2015",
AccountName: "Account 1"
},
{
Amount: 458997.32,
Year: "2016",
Name: "Account 2"
},
]
}
The 2nd object I am placing data into looks like:
[
{
"name": "Account 1",
"data": [
0,
0
],
},
{
"name": "Account 2",
"data": [
0,
0
],
}
]
My goal is to take the Amount form the first object and place it in the data array of the 2nd. Each year corresponds to a value in the 'data` array.
So, the resulting updated object should look like:
[
{
"name": "Account 1",
"data": [
430140.68,
0
],
},
{
"name": "Account 2",
"data": [
0,
458997.32
],
}
]
To try to achieve this I have the following code:
const yearArrLength = yearsArr.length;
const generatedObj = new Array(yearArrLength).fill(0);
// Push name and populate data array with 0s.
for (var key of Object.keys(userData.Data)) {
var accName = userData.Data[key].AccountName;
if (!generatedObj.find(key => key.name === accName)){
generatedObj.push({'name': accName, 'data': blankDataArr});
}
}
for (var key of Object.keys(userData.Data)) {
var accName = userData.Data[key].AccountName;
var accAmount = userData.Data[key].Amount;
var accYear = userData.Data[key].Year;
// Get location of years array value
var yearArrIndex = yearsArr.indexOf(accYear);
for (var key of Object.keys(generatedObj)) {
if (generatedObj[key].name == accName) {
generatedObj[key].data[yearArrIndex] = accAmount;
}
}
}
However, this seems to populate all of the data array values, eg:
[
{
"name": "Account 1",
"data": [
430140.68,
458997.32
],
},
{
"name": "Account 2",
"data": [
430140.68,
458997.32
],
}
]
I'm completely stumped as to why. The if statement should be checking if there is a matching account name, but it doesn't seem to fire.
Would anyone know what I've done wrong?
It looks like you're pushing the exact same blankDataArr each time - you're not pushing a new array, you're pushing the same array to all.
For a more minimal example:
const subarr = [];
const arr = [subarr, subarr];
arr[0].push('x');
console.log(JSON.stringify(arr));
// both items in `arr` have changed
// because both refer to the exact same subarr object
For what you're trying to do, it looks like it'd be a lot easier to make an object or Map indexed by AccountName first, that way you just have to access or create the AccountName property while iterating, and assign to the appropriate year.
const yearsArr = ['2015', '2016'];
const userData = {
Data: [
{
Amount: 430140.68,
Year: "2015",
AccountName: "Account 1"
},
{
Amount: 458997.32,
Year: "2016",
AccountName: "Account 2"
},
]
};
const dataByAccountName = new Map();
for (const { AccountName, Amount, Year } of userData.Data) {
if (!dataByAccountName.has(AccountName)) {
// Create an entirely new array:
dataByAccountName.set(AccountName, yearsArr.map(() => 0));
}
const index = yearsArr.indexOf(Year);
dataByAccountName.get(AccountName)[index] = Amount;
}
const result = [...dataByAccountName.entries()].map(([name, data]) => ({ name, data }));
console.log(result);

how to foreach array to array object in javascript

I'm very confused about doing foreach array to array object in Javascript, I already did a lot of research about foreach object in Javascript and I tried many ways but nothing works. All that I'm trying to achieve is to have data JSON like this :
[
{
"name": "First Data",
"data": [
{
"y": 95,
"total":100,
"md": "1",
"name": "National",
"drillup" : 'level0',
"drilldown" : "3",
"next" : "level2"
}
]
}
,{
"name": "Second Data",
"data": [
{
"y": 95,
"total":100,
"md": "1",
"name": "National",
"drillup" : 'National',
"drilldown" : "3",
"next" : "level2"
}
]
}
]
and I tried to do foreach based on some finding of my research but the result wasn't like what I want or like what I'm try to achieve ..
and here is the script that I tried :
dataFirstSecond = await informationModel.getdata();
Object.entries(dataRegularSecondary).forEach(entry => {
const [key, value] = entry;
returnData[key] = [
{
name: value.name,
data: [{
y: value.y,
total: value.total_ada,
next: 'level_2',
drilldown: true,
}]
}]
});
and here is the result or the output of my script that I try it :
{
"0": [
{
"name": "First Data",
"data": [
{
"y": 22.973,
"total": 17,
"next": "level_2",
"drilldown": true
}
]
}
],
"1": [
{
"name": "Second Data",
"data": [
{
"y": 5.4054,
"total": 4,
"next": "level_2",
"drilldown": true
}
]
}
]
}
can someone help me to achieve the data that I want?
returnData[key] = [{ ... }] should just be returnData.push({ ... }), and make sure returnData is an array (e.g. returnData = [])
If the function informationModel.getdata(); returns an Object you could use the method JSON.stringify(Object) to easily convert and Object to JSON. For example you could try to do to convert this Object to a String then cast the String to JSON.
let JSONString = JSON.stringify(informationModel.getdata());
let JSON_Object = JSON.parse(JSONString);
If dataRegularSecondary is an array and not an object you could use map:
dataRegularSecondary.map(value => {
return {
name: value.name,
data: [{
y: value.y,
total: value.total_ada,
next: 'level_2',
drilldown: true,
}]
}
}
Your question is how to forEach array to array object. Then that means dataRegularSecondary is an array, right? Object.entries returns an array of key value pairs. If you pass an array to that method, it will return the indices as keys and the items as values.
const arr = ['hello', 'world'];
Object.entries(arr); // [['0', 'hello'], ['1', 'world']]
Skip the Object.entries and use dataRegularSecondary directly for forEach.
As for your output, it looks like returnData is an object as well. Make sure it's an array and just push the data into that.
dataRegularSecondary.forEach(value => {
returnData.push({
name: value.name,
data: [{
y: value.y,
total: value.total_ada,
next: 'level_2',
drilldown: true,
}],
});
});
Or you can use map as well.
const returnData = dataRegularSecondary.map(value => ({
name: value.name,
data: [{
y: value.y,
total: value.total_ada,
next: 'level_2',
drilldown: true,
}],
}));

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

How to create a JS object and append it to an array

I have the following data :
const data=
{
"1": [
{
"sales_project_id": 5,
"sales_project_name": "name",
"sales_project_est_rev": "123.00",
"project_status": {
"id": 1,
"label": "Start",
"description": null
}
},
{
"sales_project_id": 6,
"sales_project_name": "name2",
"sales_project_est_rev": "123.00",
"project_status": {
"id": 1,
"label": "Start",
"description": null
}
}
],
"2": [],
"4": []
}
These data are grouped in my backend based on their Status , in this case im only showing 2 status , but they are dynamic and can be anything the user defines.
What i wish to do is to transform the above data into the format below :
const data =
{
columns: [
{
id: // id of status here,
title: //label of status here,
cards: [
{
id : //sales_project_id here,
title: //sales_project_name here,
},
]
},
{
id: // id of status here,
title: //label of status here,
cards: [
{
id : //sales_project_id here,
title: //sales_project_name here,
},
]
}
]}
My guess would be to iterate over the data , however i am pretty unfamiliar with doing so , would appreciate someone's help!
Here is what i could come up with so far:
const array = []
Object.keys(a).map(function(keyName, keyIndex) {
a[keyName].forEach(element => {
#creating an object of the columns array here
});
})
after some trial and error , manage to accomplish this , however , im not sure if this is a good method to do so.
Object.keys(projects).map(function(keyName, keyIndex) {
// use keyName to get current key's name
// and a[keyName] to get its value
var project_object = {}
project_object['id'] = projects[keyName][0].id
project_object['title'] = projects[keyName][0].label
project_object['description'] = projects[keyName][0].description
console.log( projects[keyName][1])
var card_array = []
projects[keyName][1].forEach(element => {
var card = {}
card["id"] = element.sales_project_id
card["title"] = element.sales_project_name
card["description"] = element.sales_project_est_rev
card_array.push(card)
});
project_object["cards"] = card_array
array.push(project_object)
})
Im basically manipulating some the scope of the variables inorder to achieve this
See my solution, I use Object.keys like you, then I use reduce:
const newData = { columns: Object.keys(data).map((item) => {
return data[item].reduce((acc,rec) => {
if (typeof acc.id === 'undefined'){
acc = { id: rec.project_status.id, title: rec.project_status.label, ...acc }
}
return {...acc, cards: [...acc.cards, { id:rec.sales_project_id, title:rec.sales_project_name}]}
}, {cards:[]})
})}
See full example in playground: https://jscomplete.com/playground/s510194
I'd just do this. Get the values of data using Object.values(data) and then use reduce to accumulate the desired result
const data=
{
"1": [
{
"sales_project_id": 5,
"sales_project_name": "name",
"sales_project_est_rev": "123.00",
"project_status": {
"id": 1,
"label": "Start",
"description": null
}
},
{
"sales_project_id": 6,
"sales_project_name": "name2",
"sales_project_est_rev": "123.00",
"project_status": {
"id": 1,
"label": "Start",
"description": null
}
}
],
"2": [],
"4": []
};
const a = Object.values(data)
let res =a.reduce((acc, elem)=>{
elem.forEach((x)=>{
var obj = {
id : x.project_status.id,
title : x.project_status.label,
cards : [{
id: x.sales_project_id,
title: x.sales_project_name
}]
}
acc.columns.push(obj);
})
return acc
},{columns: []});
console.log(res)

Categories

Resources