How to get these json nested values using angular? - javascript

I have this json response:
{
"tags": [
{
"name": "SolarData",
"results": [
{
"groups": [
{
"name": "type",
"type": "number"
}
],
"attributes": {
"customer": [
"Acme"
],
"host": [
"server1"
]
},
"values": [
[
1429950000000,
46,
3
],
[
1429960000000,
62,
3
],
[
1429970000000,
183,
3
],
[
1429980000000,
156,
3
],
[
1429990000000,
205,
3
]
]
}
],
"stats": {
"rawCount": 5
}
}
]
}
and I want to be able to only get the first two items of every value part of the item. Foe example I want to return [[1429950000000,46],[1429960000000,62],[1429970000000,183],.....] in a scope variable so I can eventually use it for a graph. I am new to angular and web dev in general but this is the way I've tried it so far.
$http({
url: 'file.json',
method: 'POST',
data: '(query data here)'
}).then(function(data, status){
$scope.solarData = data.tags.results.values;
conosle.log($scope.solarData);
});

You can use map:
var custom = data.tags[0].results[0].values.map(function(values) {
return [values[0], values[1]];
});
You can use slice if you want to return a lot of items or a variable number of them like
return values.slice(0, 2);
//---------------------^ replace this
var data = {
"tags": [{
"name": "SolarData",
"results": [{
"groups": [{
"name": "type",
"type": "number"
}],
"attributes": {
"customer": [
"Acme"
],
"host": [
"server1"
]
},
"values": [
[
1429950000000,
46,
3
],
[
1429960000000,
62,
3
],
[
1429970000000,
183,
3
],
[
1429980000000,
156,
3
],
[
1429990000000,
205,
3
]
]
}],
"stats": {
"rawCount": 5
}
}]
}
var custom = data.tags[0].results[0].values.map(function(values) {
return [values[0], values[1]];
});
console.log(custom);

var requirementArray = new Array();
for (i = 0; i < $scope.solarData.length ; i++) {
var pare = new Array();
pare.push($scope.solarData[i][0]);
pare.push($scope.solarData[i][1]);
requirementArray.push(pare);
}
requirementArray will be :
[[1429950000000,46],[1429960000000,62],[1429970000000,183],.....]

You can use Array.map for that:
$http({
url: 'file.json',
method: 'POST',
data: '(query data here)'
}).then(function(data, status){
$scope.solarData = data.tags[0].results[0].values.map(
function(curVal, index, arr) {
return [curVal[0], curVal[1]];
}
);
conosle.log($scope.solarData);
});

Related

JS How to remove an object from array in a forEach loop?

I have a data object with following contents:
{
"content": {
"id": "someID",
"type": "unit",
"method": "xyz",
"blocks": [{
"key": "blue",
"data": [
"Array"
]
}, {
"key": "red",
"data": [
"Array"
]
}, {
"key": "yellow",
"data": [
"Array"
]
}, {
"key": "black",
"data": [
"Array"
]
}],
"notes": "abc"
}
}
I want to remove block that has key yellow, by looping over blocks, rest of the data should be preserved as is. So expected end result would be
{
"content": {
"id": "someID",
"type": "unit",
"method": "xyz",
"blocks": [{
"key": "blue",
"data": [
"Array"
]
}, {
"key": "red",
"data": [
"Array"
]
}, {
"key": "black",
"data": [
"Array"
]
}],
"notes": "abc"
}
}
Data is dynamic so I dont know what would be returned, it might have a match for my condition or it might not.
I've tried a bunch of approaches but nothing seems to have worked so far. I can use lodash too if its any easier. None of those seems to be working. Any help/direction is appreciated
1. Using **delete**
const deleteUnwantedBlock = contentObj => {
const updatedData = contentObj;
const blocks = _.get(updatedData, 'blocks', []);
blocks.forEach(block => {
if (block.key.includes('yellow')) {
delete updatedData.block;
}
});
return updatedData;
};
console.log(deleteUnwantedBlock(data.content));```
2. Using rest operator:
const deleteUnwantedBlock = contentObj => {
const blocks = _.get(contentObj, 'blocks', []);
blocks.forEach(block => {
if (block.key.includes('yellow')) {
let { block, ...restOfTheData } = updatedData;
}
return { ...updatedEntry };
});
};
console.log(deleteUnwantedBlock(data.content));
You just need to filter:
const obj = {
"content": {
"id": "someID",
"type": "unit",
"method": "xyz",
"blocks": [{
"key": "blue",
"data": [
"Array"
]
}, {
"key": "red",
"data": [
"Array"
]
}, {
"key": "yellow",
"data": [
"Array"
]
}, {
"key": "black",
"data": [
"Array"
]
}],
"notes": "abc"
}
};
obj.content.blocks = obj.content.blocks.filter(({ key }) => key !== 'yellow');
console.log(obj);

How to sort a nested array using lodash

I have a collection of objects in this array and I need to order them by the 'order' key (asc). Is there a way to sort the objects inside the array and then return the whole array? I am relying on the order as I'm using it in a v-for with a :key.
[
{
"id":0,
"type":"Header",
"order":1,
"props":{
"order":0,
"id":0,
"section_id":0
},
"data":{
"header":""
},
"component":"header-block"
},
{
"id":1,
"type":"Header",
"order":0,
"props":{
"order":1,
"id":1,
"section_id":0
},
"data":{
"header":""
},
"component":"header-block"
}
],
[
//Another collection of objects
]
I am currently doing this -
getters: {
sorted: state => {
return _.orderBy(state.experience_sections, function(block) {
if(block.experience_blocks[0]) {
return block.experience_blocks[0].order;
}
});
}
}
The solution above does not seem to order the objects by 'asc' order. Am I on the right track?
Thanks!
P.S. Stack is telling me that is a possible duplicate question but I'm at a loss after hours of searching. My apologies if I missed an already answered question.
Just in case you want plain javascript solution.. using Array.forEach
I have also extended your array to contain more data
var arr = [[
{
"id":0,
"type":"Header",
"order":1,
"props":{
"order":0,
"id":0,
"section_id":0
},
"data":{
"header":""
},
"component":"header-block"
},
{
"id":1,
"type":"Header",
"order":0,
"props":{
"order":1,
"id":1,
"section_id":0
},
"data":{
"header":""
},
"component":"header-block"
}
], [
{
"id":0,
"type":"Header",
"order":2,
"props":{
"order":0,
"id":0,
"section_id":0
},
"data":{
"header":""
},
"component":"header-block"
},
{
"id":1,
"type":"Header",
"order":1,
"props":{
"order":1,
"id":1,
"section_id":0
},
"data":{
"header":""
},
"component":"header-block"
}
]]
arr.forEach(d => d.sort((a,b) => a.order - b.order))
console.log(arr)
You should also consider orderBy method from lodash since you could easily change from asc to desc sort order if you would want to at a later date or have it via a variable being passed through the UI etc:
const data = [ [{ "id": 0, "type": "Header", "order": 1, "props": { "order": 0, "id": 0, "section_id": 0 }, "data": { "header": "" }, "component": "header-block" }, { "id": 1, "type": "Header", "order": 0, "props": { "order": 1, "id": 1, "section_id": 0 }, "data": { "header": "" }, "component": "header-block" } ], [{ "id": 0, "type": "Header", "order": 2, "props": { "order": 0, "id": 0, "section_id": 0 }, "data": { "header": "" }, "component": "header-block" }, { "id": 1, "type": "Header", "order": 1, "props": { "order": 1, "id": 1, "section_id": 0 }, "data": { "header": "" }, "component": "header-block" } ] ]
console.log('asc:', _.map(data, x => _.orderBy(x, 'order'))) // asc order
console.log('desc:', _.map(data, x => _.orderBy(x, 'order', 'desc'))) // desc
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
Will sort each subarray in an array
const sortedArr = _.map(arr, subArray => _.sortBy(subArray, "order"));
Deep sorting using lodash
const sortedArray = _.orderBy(items, [(item) => {
const nestedObj = _.get(item, 'props');
item['props'] = _.orderBy(nestedObj,'order','desc');
return item['order'];
}], 'desc');

iterate through Json array without having a key

First of all, this question might have been asked several times already, but every thread I found didn't help me. I would appreciate if one could rewrite my function below.
I have the following array with Json objects.
The goal is to get the "url" values. Right now I get every value from that array.
a = [{
"result": [{
"name": [
"name"
],
"url": [
"www.bar.com"
]
},
{
"name": [
"name 2"
],
"url": [
"www.bar.org"
]
},
{
"name": [
"name 1"
],
"url": [
"www.bar.biz"
]
},
{
"name": [
"name 3"
],
"url": [
"www.bar.jp"
]
}
]
}];
document.getElementById("foo").innerHTML = "How to explicitly get the url value?'";
loopThrough(a);
function loopThrough(obj) {
for (var key in obj) {
// skip loop if the property is from prototype
if (!obj.hasOwnProperty(key)) continue;
if (typeof obj[key] !== 'object') {
console.log(obj[key]);
} else {
loopThrough(obj[key]);
}
}
}
<div id="foo">
</div>
How would I access each "url" element in this array?
Maybe there is also a smarter solution than this.
Thank you in advance.
a = [{
"result": [{
"name": [
"name"
],
"url": [
"www.bar.com"
]
},
{
"name": [
"name 2"
],
"url": [
"www.bar.org"
]
},
{
"name": [
"name 1"
],
"url": [
"www.bar.biz"
]
},
{
"name": [
"name 3"
],
"url": [
"www.bar.jp"
]
}
]
}];
loopThrough(a);
// Uses ES6 syntax
function loopThrough(obj) {
obj[0].result.forEach(r => console.log(r.url[0]));
}
try it yourself.
var a = [{
"result": [{
"name": [
"name"
],
"url": [
"www.bar.com"
]
},
{
"name": [
"name 2"
],
"url": [
"www.bar.org"
]
},
{
"name": [
"name 1"
],
"url": [
"www.bar.biz"
]
},
{
"name": [
"name 3"
],
"url": [
"www.bar.jp"
]
}
]
}];
var urls=a[0].result.reduce(function(urls,it){
return urls.concat(it.url);
},[]);
console.log(urls);

How to convert string to number in a nested array?

I have the following array of objects which has an array inside an
array. the values are in the string, I want it to be a number. What is
the best possible solution to do that in JavaScript.
[
{
"key": "America",
"values": [
[
"1469664000000",
"1"
],
[
"1469750400000",
"13"
],
[
"1469836800000",
"2"
],
[
"1469923200000",
"1"
],
[
"1470009600000",
"1"
],
[
"1470096000000",
"1"
]
]
},
{
"key": "India",
"values": [
[
"1469750400000",
"1"
]
]
},
{
"key": "China",
"values": [
[
"1469664000000",
"2"
],
[
"1469836800000",
"1"
],
[
"1470096000000",
"12"
]
]
},
{
"key": "Africa",
"values": [
[
"1470096000000",
"1"
]
]
},
{
"key": "UK",
"values": [
[
"1469664000000",
"3"
],
[
"1469750400000",
"3"
],
[
"1469836800000",
"1"
],
[
"1469923200000",
"2"
],
[
"1470009600000",
"4"
],
[
"1470096000000",
"2"
]
]
}
]
var data = [{"key":"America","values":[["1469664000000","1"],["1469750400000","13"],["1469836800000","2"],["1469923200000","1"],["1470009600000","1"],["1470096000000","1"]]},{"key":"India","values":[["1469750400000","1"]]},{"key":"China","values":[["1469664000000","2"],["1469836800000","1"],["1470096000000","12"]]},{"key":"Africa","values":[["1470096000000","1"]]},{"key":"UK","values":[["1469664000000","3"],["1469750400000","3"],["1469836800000","1"],["1469923200000","2"],["1470009600000","4"],["1470096000000","2"]]}];
data.forEach(function (o) {
o.values.forEach(function (values) {
values.forEach(function (value, i) {
values[i] = parseInt(value, 10);
});
});
});
console.log(JSON.stringify(data, null, 4));
var data = [{"key":"America","values":[["1469664000000","1"],["1469750400000","13"],["1469836800000","2"],["1469923200000","1"],["1470009600000","1"],["1470096000000","1"]]},{"key":"India","values":[["1469750400000","1"]]},{"key":"China","values":[["1469664000000","2"],["1469836800000","1"],["1470096000000","12"]]},{"key":"Africa","values":[["1470096000000","1"]]},{"key":"UK","values":[["1469664000000","3"],["1469750400000","3"],["1469836800000","1"],["1469923200000","2"],["1470009600000","4"],["1470096000000","2"]]}];
data = data.map(function(t){
var newVals = t.values.map(function(vs){
return vs.map(function(v){
return parseInt(v, 10);
});
});
return {'key': t.key, values: newVals};
});
console.log(JSON.stringify(data));
You can use JSON.parse(your json object
or maybe use two forEachs

jQuery Flot graph not loading (JSON data)

I'm having the following issue while using Flot for a graph. The input for the graph is JSON, retrieved from a server.
The ajax call to get the data is:
$.ajax({
url: 'graphdata.do',
dataType: 'json',
success: function (retData) {
renderGraph(retData);
}
});
And the renderGraph function:
function renderGraph(datasets)
{
var data = [];
console.log(datasets);
$('.cbScenarioSelected').each(function(index) {
if($(this).is(':checked')){
var id = $(this).prop("id"); //this works, right id is returned
data.push(datasets[id]);
}
});
$.plot($("#graph1"), data, {
yaxis: { min: 0 },
xaxis: { tickDecimals: 0 }
});
}
The data returned from the server:
{
"1": {
"label": "Name1",
"data": "[[133,64.8000030517578],[134,64.8099975585938],[135,65.0999984741211],[136,66.0699996948242],[137,66.129997253418],[138,66.2600021362305],[139,66.6699981689453],[140,66.9400024414063],[141,67.4100036621094],[142,68.0599975585938], [143,68.0800018310547],[144,68.3600006103516],[145,68.8699951171875], [146,69.4899978637695],[147,69.6500015258789],[148,70.0999984741211], [149,70.7400054931641],[150,70.9199981689453],[151,71.1500015258789], [152,71.7000045776367],[153,72.0899963378906],[154,72.4799957275391], [155,73.2700042724609],[156,73.3000030517578],[157,73.4599990844727], [158,73.5100021362305],[159,74.6799926757813],[160,77.5200042724609], [161,77.8399963378906],[162,78.8300018310547]]"
},
"2": {
"label": "Name2",
"data": "[]"
},
"3": {
"label": "Name3",
"data": "[]"
}
}
The graph container is shown, and so are the labels. The lines in the graph are not shown.
Anyone have an idea? I think it has something to do with the quotes around the "data" tag in the returned data, but I have no idea how to fix it.
In your JSON, data part are string because of they are encapsulated with quotes.
In fact, the json should look like (without quotes)
{
"1": {
"label": "Name1",
"data": [
[
133,
64.8000030517578
],
[
134,
64.8099975585938
],
[
135,
65.0999984741211
],
[
136,
66.0699996948242
],
[
137,
66.129997253418
],
...
]
},
"2": {
"label": "Name2",
"data": []
},
"3": {
"label": "Name3",
"data": []
}
}

Categories

Resources