Related
I have an array of objects each with a groupName key/value and then an item key with an array of objects as it's value.
I'm trying to use .reduce() with a forEach to iterate over the main array and merge all of the item values into a new Object with a single groupName and an items array containing all the original item values.
Every time I run the function I only get back the first value and I'm trying to figure out what I'm doing wrong.
Current Function:
const testMerge = moviesArray.reduce((acc, curr) => {
const { items } = curr;
items.forEach((el) => (acc[el] = el));
return acc;
}, {});
console.log('Test merge: ', testMergeObjects);
// returns [object Object]: groupName: The Town, year: 2010
moviesArray:
[
{
"groupName": "comedy",
"items": [
{
"name": "I Love You, Man",
"year": "2009"
}
]
},
{
"groupName": "sci fi",
"items": [
{
"name": "The Matrix",
"year": "1999"
},
{
"name": "Looper",
"year": "2012"
}
]
},
{
"groupName": "crime thriller",
"items": [
{
"name": "The Town",
"year": "2010"
}
]
}
]
Desired Result:
[
"groupName": "movies",
"items": [
{
"name": "I Love You, Man",
"year": "2009"
},
{
"name": "The Matrix",
"year": "1999"
},
{
"name": "Looper",
"year": "2012"
},
{
"name": "The Town",
"year": "2010"
}
]
]
You can use array#map and array#concat to merge items in movie array.
const data = [ { "groupName": "comedy", "items": [ { "name": "I Love You, Man", "year": "2009" } ] }, { "groupName": "sci fi", "items": [ { "name": "The Matrix", "year": "1999" }, { "name": "Looper", "year": "2012" } ] }, { "groupName": "crime thriller", "items": [ { "name": "The Town", "year": "2010" } ] } ],
items = [].concat(...data.map(({items}) => items)),
output = { groupName: "movies", items}
console.log(output);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I have the JSON like
var resultJSON = `{
"data": {
"total": 1,
"list_name": "title",
"title": {
"id": 53,
"name": "Sonu",
"mobileNo": "6543213456",
"address": "Greeny Pathway",
"city": "NewYork",
"mode": "Weekly",
"duration": "15",
"qty": null
},
"download": [{
"time": "16789042",
"date": "26 - 01 - 2020"
}]
}
}`;
I expect the output:
{
"total": "1",
"list_name": "title",
"name": "sonu",
"mobileno": "6543213456"
}
Here "list_name": "title" is dynamic, sometimes it will come "list_name": "book", based on that above mentioned response I want to get.
Something like this? I had to fix your invalid JSON
You can make it more clever if you study https://javascript.info/destructuring-assignment in depth
const resultJSON = `{
"data": {
"total": 1,
"list_name": "title",
"title": {
"id": 53,
"name": "Sonu",
"mobileNo": "6543213456",
"address": "Greeny Pathway",
"city": "NewYork",
"mode": "Weekly",
"duration": "15",
"qty": null
},
"download": [{
"time": "16789042",
"date": "26-01-2020"
}]
}
}`
const data = JSON.parse(resultJSON).data
const content = data[data.list_name];
let newObj = {}
newObj["total"] = data["total"];
newObj["list_name"] = data["list_name"];
newObj["name"] = content["name"];
newObj["mobileNo"] = content["mobileNo"];
console.log(newObj)
I'm looking for a way to generate an HTML table from a JSON data.
I'm limitated with tooling options because we use CMS, so I can only use JS, JQuery and ApacheVelocity (without making new templates, only using the 'syntax').
Well, I get this kind of JSON data from remote API:
{
"code": 0,
"rid": "0",
"data": {
"subid": "-7766883411351472375",
"data": {
"region": {
"123": {
"alias": "Europe",
"game": {
"11811809": {
"id": 11811809,
"team1_name": "Zorya Luhansk",
"team2_name": "SC Braga",
"market": {
"188597332": {
"type": "P1XP2",
"name": "Ganador del Partido",
"event": {
"624566458": {
"price": 2.39,
"name": "W1"
},
"624566459": {
"price": 3.01,
"name": "X"
},
"624566460": {
"price": 2.82,
"name": "W2"
}
}
}
}
},
"11811810": {
"id": 11811810,
"team1_name": "Olympiacos Piraeus",
"team2_name": "FC Luzern",
"market": {
"188597340": {
"type": "P1XP2",
"name": "Ganador del Partido",
"event": {
"624566476": {
"price": 1.34,
"name": "W1"
},
"624566477": {
"price": 4.29,
"name": "X"
},
"624566478": {
"price": 7.92,
"name": "W2"
}
}
}
}
},
"11844220": {
"id": 11844220,
"team1_name": "NK Domzale",
"team2_name": "FC Ufa",
"market": {
"189338624": {
"type": "P1XP2",
"name": "Ganador del Partido",
"event": {
"626913821": {
"price": 2.35,
"name": "W1"
},
"626913822": {
"price": 2.86,
"name": "X"
},
"626913823": {
"price": 3.03,
"name": "W2"
}
}
}
}
}
}
}
}
}
}
}
The first problem I face are those numeric indexes.
The only way to make reference to this is like this:
arr_from_json.data.data.region[123].game[11844220].team1_name
It is ok if we only have a few "games" extracted, even 100 games. But it is impossible to keep it updated with thousands of games who are constantly being updated.
Is there some way for iterarte through this ugly JSON structure?
Many thanks
Edit:
I want to create a table with the distinct games:
Zorya Luhansk - SC Braga
W1 X W2
2.39 3.01 2.82
Most important data/keys to me are: both team names, name of the possible outcome and price.
You can convert those indexed objects into traditional arrays using a helper function, then iterate over the data in a more natural way after transforming it. See below for an example using Array.map and the helper function keysToArray(obj){ return Object.keys(obj).map(key => obj[key]); }
const resp = {
"code": 0,
"rid": "0",
"data": {
"subid": "-7766883411351472375",
"data": {
"region": {
"123": {
"alias": "Europe",
"game": {
"11811809": {
"id": 11811809,
"team1_name": "Zorya Luhansk",
"team2_name": "SC Braga",
"market": {
"188597332": {
"type": "P1XP2",
"name": "Ganador del Partido",
"event": {
"624566458": {
"price": 2.39,
"name": "W1"
},
"624566459": {
"price": 3.01,
"name": "X"
},
"624566460": {
"price": 2.82,
"name": "W2"
}
}
}
}
},
"11811810": {
"id": 11811810,
"team1_name": "Olympiacos Piraeus",
"team2_name": "FC Luzern",
"market": {
"188597340": {
"type": "P1XP2",
"name": "Ganador del Partido",
"event": {
"624566476": {
"price": 1.34,
"name": "W1"
},
"624566477": {
"price": 4.29,
"name": "X"
},
"624566478": {
"price": 7.92,
"name": "W2"
}
}
}
}
},
"11844220": {
"id": 11844220,
"team1_name": "NK Domzale",
"team2_name": "FC Ufa",
"market": {
"189338624": {
"type": "P1XP2",
"name": "Ganador del Partido",
"event": {
"626913821": {
"price": 2.35,
"name": "W1"
},
"626913822": {
"price": 2.86,
"name": "X"
},
"626913823": {
"price": 3.03,
"name": "W2"
}
}
}
}
}
}
}
}
}
}
}
function keysToArray(obj){ return Object.keys(obj).map(key => obj[key]); }
function parseGameData(data){
return keysToArray(data.region).map(obj => keysToArray(obj.game).map(obj => {
obj.market = keysToArray(obj.market).map(obj => {
return {
name: obj.name,
event: keysToArray(obj.event)
}
})
return obj
}))
}
console.log(parseGameData(resp.data.data))
I have following input json payload,
{
"Products": {
"Product": [
{
"ProductID": 458761,
"Designation": "CB 024-2001",
"EntryDate": "2002-01-20T19:00:00.000-05:00",
"S1": "024",
"S2": 2001,
"Year": 2001
},
{
"ProductID": 458234,
"Designation": "AGRS03/08",
"EntryDate": "2008-03-05T19:00:00.000-05:00",
"S1": "03",
"S2": "08",
"Year": 2008
}
]
}
}
And now I need to transform it into the following JSON format.
[
{
"Designation": "CB 024-2001",
"EntryDate": "2002-01-20T19:00:00.000-05:00",
"ProductID": 458761,
"S1": "024",
"S2": 2001,
"Year": 2001
},
{
"Designation": "AGRS03/08",
"EntryDate": "2008-03-05T19:00:00.000-05:00",
"ProductID": 458761,
"S1": "03",
"S2": "08",
"Year": 2008
}
]
Can someone please help me to write a JavaScript to achieve this task. Any help is really appreciated.
EDIT: You changed the question :(
Assuming your original json is stored in a variable named input. This can be done using this code:
var output = input.Products.Product;
ORIGINAL: You can do this using map:
var output = input.Products.Product.map(function(inObj) {
return {
"Designation": inObj.Designation,
"EntryDate": inObj.EntryDate,
"S1": inObj.S1,
"S2": inObj.S2,
"Year": inObj.Year
}
});
This will give you the output you want - an array of objects, with the ProductIDs removed. I'm a bit rusty when it comes to working with object references, but you could possibly shorten this using delete:
var output = input.Products.Product.map(function(inObj) {
var outObj = inObj;
delete outObj.ProductID;
return outObj;
});
This will change the original input values as well though, so i wouldn't recommend it unless you don't plan on using that data again.
var first = {
"Products": {
"Product": [
{
"ProductID": 458761,
"Designation": "CB 024-2001",
"EntryDate": "2002-01-20T19:00:00.000-05:00",
"S1": "024",
"S2": 2001,
"Year": 2001
},
{
"ProductID": 458234,
"Designation": "AGRS03/08",
"EntryDate": "2008-03-05T19:00:00.000-05:00",
"S1": "03",
"S2": "08",
"Year": 2008
}
]
}
}
then:
var second = first.Products.Product;
To make it exactly like you want:
for(var i = 0; i<second.length; i++){
delete second[i].ProductID;
}
You can use this little function:
var a = {
"Products": {
"Product": [{
"ProductID": 458761,
"Designation": "CB 024-2001",
"EntryDate": "2002-01-20T19:00:00.000-05:00",
"S1": "024",
"S2": 2001,
"Year": 2001
}, {
"ProductID": 458234,
"Designation": "AGRS03/08",
"EntryDate": "2008-03-05T19:00:00.000-05:00",
"S1": "03",
"S2": "08",
"Year": 2008
}]
}
};
function newJSON(array){
var b = array.Products.Product;
b.forEach(function(e){delete e.ProductID});
return JSON.stringify(b);
}
document.write(newJSON(a));
With underscore:
var result = _.map(data.Products.Products, (product) => {
return _.omit(product, 'ProductID');
});
I am plotting a graph which contains a lot of data.
96 plots a day and the user can fetch data for a maximum range of 62 days.
I am using Amcharts to implement the same.
I need to show the user a line against the highest value of the graph.
Can someone please help me if Amcharts provides a functionality to display the max value on the graph.
Because if it doesn't i would have to reiterate the entire object just to insert the max value in every json array which doesnt seem like a good idea.
Thanks
There's no need to iterate through all of the data. When the chart builds itself, it calculates min and max values for each value axis anyway. We can tap into those auto-calculated values and add a Guide for each of them.
We can use chart's "rendered" event to do it. When this event happens, we know that the chart is build and thus minimum and maximum values are calculated.
The value axis object will contain maxReal and minReal properties, which we will use. We will add a Guide for those values to indicate highest and lowest points.
Here's how the code looks for it:
chart.addListener( "rendered", function( event ) {
// get chart and value axis
var chart = event.chart;
var axis = chart.valueAxes[0];
// create max guide
var guide = new AmCharts.Guide();
guide.value = guide.label = axis.maxReal;
guide.lineAlpha = 0.2;
guide.lineThickness = 2;
guide.lineColor = guide.color = "#00cc00";
axis.addGuide( guide );
// create min guide
var guide = new AmCharts.Guide();
guide.value = guide.label = axis.minReal;
guide.lineAlpha = 0.2;
guide.lineThickness = 2;
guide.lineColor = guide.color = "#cc0000";
axis.addGuide( guide );
} );
And here's a a complete working code of the chart:
var chart = AmCharts.makeChart( "chartdiv", {
"type": "serial",
"theme": "light",
"path": "http://www.amcharts.com/lib/3/",
"dataProvider": [ {
"year": "1969",
"value": -0.011
}, {
"year": "1970",
"value": -0.068
}, {
"year": "1971",
"value": -0.19
}, {
"year": "1972",
"value": -0.056
}, {
"year": "1973",
"value": 0.077
}, {
"year": "1974",
"value": -0.213
}, {
"year": "1975",
"value": -0.17
}, {
"year": "1976",
"value": -0.254
}, {
"year": "1977",
"value": 0.019
}, {
"year": "1978",
"value": -0.063
}, {
"year": "1979",
"value": 0.05
}, {
"year": "1980",
"value": 0.077
}, {
"year": "1981",
"value": 0.12
}, {
"year": "1982",
"value": 0.011
}, {
"year": "1983",
"value": 0.177
}, {
"year": "1984",
"value": -0.021
}, {
"year": "1985",
"value": -0.037
}, {
"year": "1986",
"value": 0.03
}, {
"year": "1987",
"value": 0.179
}, {
"year": "1988",
"value": 0.18
}, {
"year": "1989",
"value": 0.104
}, {
"year": "1990",
"value": 0.255
}, {
"year": "1991",
"value": 0.21
}, {
"year": "1992",
"value": 0.065
}, {
"year": "1993",
"value": 0.11
}, {
"year": "1994",
"value": 0.172
}, {
"year": "1995",
"value": 0.269
}, {
"year": "1996",
"value": 0.141
}, {
"year": "1997",
"value": 0.353
}, {
"year": "1998",
"value": 0.548
}, {
"year": "1999",
"value": 0.298
}, {
"year": "2000",
"value": 0.267
}, {
"year": "2001",
"value": 0.411
}, {
"year": "2002",
"value": 0.462
}, {
"year": "2003",
"value": 0.47
}, {
"year": "2004",
"value": 0.445
}, {
"year": "2005",
"value": 0.47
} ],
"valueAxes": [ {
} ],
"graphs": [ {
"id": "g1",
"bullet": "round",
"lineColor": "#d1655d",
"lineThickness": 2,
"negativeLineColor": "#637bb6",
"valueField": "value",
"bulletField": "bullet-g1",
"labelText": "[[label-g1]]"
} ],
"chartCursor": {
"categoryBalloonDateFormat": "YYYY",
"zoomable": false
},
"dataDateFormat": "YYYY",
"categoryField": "year",
"categoryAxis": {
"minPeriod": "YYYY",
"parseDates": true,
"minorGridAlpha": 0.1,
"minorGridEnabled": true
}
} );
chart.addListener( "rendered", function( event ) {
// get chart and value axis
var chart = event.chart;
var axis = chart.valueAxes[0];
// create max guide
var guide = new AmCharts.Guide();
guide.value = guide.label = axis.maxReal;
guide.lineAlpha = 0.2;
guide.lineThickness = 2;
guide.lineColor = guide.color = "#00cc00";
axis.addGuide( guide );
// create min guide
var guide = new AmCharts.Guide();
guide.value = guide.label = axis.minReal;
guide.lineAlpha = 0.2;
guide.lineThickness = 2;
guide.lineColor = guide.color = "#cc0000";
axis.addGuide( guide );
} );
#chartdiv {
width: 100%;
height: 500px;
}
<script src="http://www.amcharts.com/lib/3/amcharts.js"></script>
<script src="http://www.amcharts.com/lib/3/serial.js"></script>
<script src="http://www.amcharts.com/lib/3/themes/light.js"></script>
<div id="chartdiv"></div>