Filling an array in a component with JSON objects Angular 2 - javascript

I am trying to access keys and values in a JSON response to fill an array. This array is currently blank and is used for chart.js. The API: https://api.coindesk.com/v1/bpi/historical/close.json has keys and values that are changing every 24 hours, i.e.:
{"bpi":
{"2017-10-06":4370.245,
"2017-10-07":4437.0338,
}
}
The array 'data' needs to be filled inside the component.ts file, and not in a template or .html file
chartData = [
{ data: [], label: 'Bitcoin' },
];
To clarify, I am trying to fill the array 'data' with values such as '4370.245' which are coming from an http.get request from the above url.

Try this
chartData = [
{ data: [], label: 'Bitcoin' },
];
let arrayData = chartData[0].data;//this will return you data inside chartData
Edited as per coomment
var outputData = []
var keysArray = Object.keys(tmpObj.bpi)
for (var key in tmpObj.bpi) {
if (tmpObj.bpi.hasOwnProperty(key )) {
outputData.push(tmpObj.bpi[key])
}
}
console.log(outputData);
var tmpObj = {"bpi":
{"2017-10-06":4370.245,
"2017-10-07":4437.0338,
}
};
var outputData = []
var keysArray = Object.keys(tmpObj.bpi)
for (var key in tmpObj.bpi) {
if (tmpObj.bpi.hasOwnProperty(key )) {
outputData.push(tmpObj.bpi[key])
}
}
console.log(outputData);

Related

Trying to concat 2 objects and destruct it into a new data structure

Given the following objects:
obj1 - { min: 86, down: 95, up: 95, max: 88, … }
obj2 - { right: 35 }
I've written the following code:
Object.keys(response).forEach(key => {
let newLabel = this.getLabel(key);
let labelPanel = this.getPanel(key);
let newPair = {
[newLabel]: response[key]
};
let secondPair = {
panel: labelPanel
};
const newObj = Object.assign(newPair, secondPair);
newDataStructure = { ...newDataStructure,
...newObj
};
});
And what I'm trying to do is to run over the given object, and create a new object with the updated key name.
For example:
min: 77 ---> Minimum: 77
I am also trying to get a value and set it to the 'panel' key, then I want to create a new object with these 2 keys, like this:
{ Minimum: 99, panel: "Budget" }
By doing this destructure:
newDataStructure = { ...newDataStructure, ...newObj};
Result: I'm getting the new data structure like the following:
{Minimum: 99, panel: "Budget", down: 95, up: 95, max: 88,....}
Only the first part is getting the 'panel' key and value, but the rest are values from the 1st object.
How can I create an array of objects like this:
[{Minimum: 99, panel: "Budget"}, {Maximum: 88, panel: "Budget"}, {....}, {....}]
You need to make an array first and then keep pushing your newObj in it. Try
let newResponse = [];
Object.keys(response).forEach(key => {
let newLabel = this.getLabel(key);
let labelPanel = this.getPanel(key);
let newPair = {
[newLabel]: response[key]
};
let secondPair = {
panel: labelPanel
};
const newObj = Object.assign(newPair, secondPair);
newResponse.push(newObj);
});

Javascript get key of nested JSON object?

I have a json response that looks like the image below. I want to get all dates from the json and store in an array.
function buyOption(){
var ticker = document.getElementById('ticker').value;
fetch("https://stock-and-options-trading-data-provider.p.rapidapi.com/options/JPM", {
.then(response => response.json())
.then(data => {
dataset = data;
console.log(dataset['options'])
loadTable()
})
.catch(err => {
console.log(err);
});
function loadTable(){
expiration_dates = []
dates = dataset['options']
// console.log(JSON.parse(dates))
var keys = [];
for(var k in dates) keys.push(k);
console.log(keys)// returns ["0","1","2",3","5",6","9","10","11"]
console.log(dates[0].value) // returns undefined
}
}
goal is to have expiration_dates = ["2020-08-21","2020-08-28"]
You can try this. This will give you only the expiration dates.
var obj = {
"options": [{
"10-2-2001": "",
"someOtherProp": ""
}, {
"20-2-2001": "",
"someOtherProp": ""
}]
}
var expDates = obj.options.map(o=>Object.keys(o)[0])
console.log(expDates)
Refs:
Array.map()
Object.keys()
Try this
let result = dataSet.options.map(x => Object.keys(x));
console.log(result.flat(1))
A simple array map should do the trick and use Object.keys() array to get first key from each object in your data array
const dates = dataset['options'].map(o => Object.keys(o)[0])
console.log(dates)
<script>
const dataset = {
options: [{
'2013-12-22': {
puts: [],
calls: []
}},
{'2013-02-15': {
puts: [],
calls: []
}},
{ '2018-01-01': {
puts: [],
calls: []
}}
]
}
</script>
Something like
const options=dates.options.map(o=>
Object.keys(o).filter(k=>k.match(/^2\d{3}-\d{2}-\d{2}$/))[0]);
The idea is to loop over all options, get all keys for each of the objects and filter out the keys matching the Regexp, which is a date format, starting with 2. From the filtered keys-array I am only interested in the first element ([0]).
for(k in dates) {
keys.push((v=>{
for(let i in v) return i;
})(dates[k]));
}
Try it

Javascript push array inside object

How do I create the data array from my second api call result into the format I want?
I have a code like this
var github = require('octonode');
var client = github.client();
var userName = "octocat";
var repoName = "";
var branchName = "";
var data = [];
var branches = [];
client.get('/users/'+userName+'/repos', {}, function (err, status, body, headers) {
body.forEach(function(obj) {
repoName = obj.name;
//==============================
client.get('repos/'+userName+'/'+repoName+'/branches', {}, function (errx, statusx, bodyChild, headersx) {
bodyChild.forEach(function(objChild) {
branchName = objChild.name;
});
});
});
});
I have received repoName and branchName data as well.
I want my data format like
How to use
data.push({
name: repoName,
branches: 'branchName loooping here for every repoName'
});
so branches repetition data can be contained in my branches tag
Thank you
I guess you can do something like this:
var data = [];
client.get('/users/'+userName+'/repos', {}, function (err, status, body, headers) {
body.forEach(function(obj) {
repoName = obj.name;
client.get('repos/'+userName+'/'+repoName+'/branches', {}, function (errx, statusx, bodyChild, headersx) {
let elem = {"name": repoName, "branches": []}; //create json object for each repo
bodyChild.forEach(function(objChild) {
elem.branches.push(objChild.name); //push all branchs to that elem
});
data.push(elem); // add the elem to the data array
});
});
});
So in this case data is an object, that has a property name which is string, and another property branches which is array. If you want to push data to the property branches you can just call the push() function on it.
Please check the example below:
let data = {
name: "repoName",
branches: [
{
name: "foo"
}
]
}
data.branches.push(
{
name: "bar"
}
);
console.log(data);

How to add attribute to the root of JSON object consists of array of objects?

How to add attribute to the root of JSON object consists of array of objects?
If my JSON object something like that:
[
{
"Id":"f2ac41c5-b214-48f6-ad40-9fc35c1aaad9",
"Name":"W",
"NumberOfWorkHours":8,
"NumberOfShortDays":1,
"WorkTimeRegulationId":"f5833075-2847-4cc3-834d-6138dd0dcd99"
},
{
"Id":"5c267601-fcf2-4735-9e49-b4def3981648",
"Name":"S",
"NumberOfWorkHours":6,
"NumberOfShortDays":0,
"WorkTimeRegulationId":"8d14580e-278f-41d1-9239-8874be792580"
}
]
I do the following:
worktimeJSON.Id = $('.Js-WorkTime-id').val();
worktimeJSON.Name = $('.Js-WorkTime-name').val();
worktimeJSON.NumberOfAvailableRotations = $('.Js-WorkTime-rotations').val();
And make sure that the jQuery fetching data from the inputs but this doesn't work.
This will change property of all object in array if you want to change in particular then use index for this for exp->
worktimeJSON[0].Id = $('.Js-WorkTime-id').val();
worktimeJSON[0].Name = $('.Js-WorkTime-name').val();
worktimeJSON[0].NumberOfAvailableRotations = $('.Js-WorkTime-rotations').val();
var worktimeJSON = [
{
"Id":"f2ac41c5-b214-48f6-ad40-9fc35c1aaad9",
"Name":"W",
"NumberOfWorkHours":8,
"NumberOfShortDays":1,
"WorkTimeRegulationId":"f5833075-2847-4cc3-834d-6138dd0dcd99"
},
{
"Id":"5c267601-fcf2-4735-9e49-b4def3981648",
"Name":"S",
"NumberOfWorkHours":6,
"NumberOfShortDays":0,
"WorkTimeRegulationId":"8d14580e-278f-41d1-9239-8874be792580"
}
];
worktimeJSON = worktimeJSON.map(function(val){
val.Id = $('.Js-WorkTime-id').val();
val.Name = $('.Js-WorkTime-name').val();
val.NumberOfAvailableRotations = $('.Js-WorkTime-rotations').val();
return val;
});
Push can do the job.
let worktimeJSON = [
{
"Id":"f2ac41c5-b214-48f6-ad40-9fc35c1aaad9",
"Name":"W",
"NumberOfWorkHours":8,
"NumberOfShortDays":1,
"WorkTimeRegulationId":"f5833075-2847-4cc3-834d-6138dd0dcd99"
},
{
"Id":"5c267601-fcf2-4735-9e49-b4def3981648",
"Name":"S",
"NumberOfWorkHours":6,
"NumberOfShortDays":0,
"WorkTimeRegulationId":"8d14580e-278f-41d1-9239-8874be792580"
}
];
worktimeJSON.push
({
id: "someID",
name: "toto",
WorkTimeRegulationId: 42
});
console.log(worktimeJSON);
I structure my object like this:
let WorkTimeRegulationViewModelJSON = {
Id: $('.Js-WorkTimeRegulation-id').val(),
Name: $('.Js-WorkTimeRegulation-name').val(),
NumberOfAvailableRotations: $('.Js-WorkTimeRegulation-rotations').val(),
AssignedWorkTimes: JSON.parse(worktimeJSON)
};

How to extract data from json and inject it into chart?

I am making a bar chart component which I import in my app.js. My JSON data contains cricket match information i.e season and runs (i.e runs scored in that season). On Y-axis the height of bar will be sum of all the runs in particular season and on X-axis the labels would be the season.
For below JSON example:
season 2008 -> runs = 100+200=300
season 2009 -> runs = 300
season 2010 -> runs = 1100
season 2011 -> runs = 100
JSON data:
[
{
"season":2008,
"runs":100
},
{
"season":2008,
"runs":200
},
{
"season":2009,
"runs":300
},
{
"season":2010,
"runs":600
},
{
"season":2010,
"runs":500
},
{
"season":2011,
"runs":100
}
]
Chart component:
import React, { Component } from 'react';
import ChartistGraph from 'react-chartist';
const ChartData = {
//labels are the season
labels: [ ],
series: [
// runs will be injected here
],
distributeSeries: true
}
const options = {
width: 720,
height: 400
}
class Chart extends Component {
render(){
return(
<div>
<ChartistGraph data={ChartData} type={'Bar'} options={options}/>
</div>
)}
}
export default Chart;
Instead of hardcoding the data from JSON data how can I inject season as labels and runs as series. I tried using for loop but I was not able to get sum of runs for a particular season. eg: for season 2008 it should be 100+200=300 i.e label=2008 and series element corresponding to it will be 300.
Note: For given JSON data series will be :
series:[300, 300, 1100, 100]
using array reduce to combine the seasons, and another reduce to create the two arrays
var json = `[
{
"season":2008,
"runs":100
},
{
"season":2008,
"runs":200
},
{
"season":2009,
"runs":300
},
{
"season":2010,
"runs":600
},
{
"season":2010,
"runs":500
},
{
"season":2011,
"runs":100
}
]`
var data = Object.entries(JSON.parse(json).reduce((acc, {season, runs}) => (acc[season] = (acc[season] || 0) + runs, acc), {}))
.reduce((acc, [labels, series]) => (acc.labels.push(labels), acc.series.push(series), acc),{labels: [], series:[]})
console.log(data)
Broken down in ES5, step by step
var json = `[
{
"season":2008,
"runs":100
},
{
"season":2008,
"runs":200
},
{
"season":2009,
"runs":300
},
{
"season":2010,
"runs":600
},
{
"season":2010,
"runs":500
},
{
"season":2011,
"runs":100
}
]`
var data = JSON.parse(json); // because JSON is a string representation of an javascript object
var data1 = data.reduce(function (acc, item) {
var season = item.season,
runs = item.runs;
acc[season] = acc[season] || 0; // add a season as a key
acc[season] += runs; // add runs
return acc;
}, {});
console.log(data1);
var data2 = Object.entries(data1); // make an array of [[label, runs],[label, runs]...]
console.log(data2);
var data3 = data2.reduce(function (acc, item) { // each item is an array of [year, total runs]
var labels = item[0],
series = item[1];
acc.labels.push(labels);
acc.series.push(series);
return acc;
}, { labels: [], series: [] }); // initialise the return object
console.log(data3);
Create new array, loop through all elements of current array, parse them by their key and see if value is unique in our new array, if it's not add to that, if it is create new element.
function fillGraph(data){
var newArray = []; //creating new, empty array
for(var i = 0; i < data.length; i++){ //going through all elements of data array
if(newArray.hasOwnProperty(data[i]["season"]){ //if it already has that season
newArray["season"] += data[i]["runs"]; //add runs to the current season
}else{
newArray.push({data[i]["season"] : data[i]["runs"]}); //if not create new object with key name as a season name and assign runs
}
}
for(var i in newArray) { //go through our new array
chartData.labels.push(i); //push key name of current array element into graph labels property
chartData.series.push(newArray[i]); //push value of current array element into graph series property
});
}
Sharing my take on the task
<script>
// in the url variable I use a link to my JSON, so might try you by
// firstly uploading your JSON at myjson.com
let url = 'https://api.myjson.com/bins/8x9l7';
fetch(url).then(res => res.json()).then((out) => {
// here you might try console.log(out); to check the correctness of
// displaying your JSON imported via URL
convertJsonToData(out);
}).catch(err => { throw err });
let data = {
labels: [],
series: [[]]
};
function convertJsonToData(jsonData) {
for (let x in jsonData) {
data.labels.push(jsonData[x].transactTime); //transactTime and walletBalance are keys in my JSON, you will have yours
data.series[0].push(jsonData[x].walletBalance);
};
// here you might try console.log(data); to check the correctness of
// data display taken from JSON and modified to use in chart
return data;
};
let options = {
showPoint: false,
lineSmooth: true,
fullWidth: true,
height: 700,
showArea:true,
};
new Chartist.Line('.ct-chart', data, options);
</script>

Categories

Resources