I'm trying to figure out how to access the last index of a nested array. The array I am working with is provided by an API call and is VERY LARGE so I'll shorten it below for convenience.
The array:
{
"result": {
"86400": [
[
1381190400,
123.610000,
123.610000,
123.610000,
123.610000,
0.100000,
0.0
],
[
1381276800,
123.610000,
124.190000,
123.900000,
124.180000,
3.991600,
0.0
],
...
[
1600646400,
11078,
11078,
10906.9,
10950.4,
623.00835437,
6841501.73480653
]
]
},
"allowance": {
"cost": 0.015,
"remaining": 9.985,
"upgrade": "For unlimited API access, create an account at ________"
}
}
I would like to access the last index of ['result']['86400'] , which contains:
[
1600646400,
11078,
11078,
10906.9,
10950.4,
623.00835437,
6841501.73480653
]
I am using Flutter in my code, so here is what I have tried:
http.Response historicalResponse = await http.get(historicalRequestURL);
var decodedHistorical = jsonDecode(historicalResponse.body);
var historicalPrice = decodedHistorical['result']['86400'.length - 1][0];
print(historicalPrice);
This causes a few errors stating:
"NoSuchMethodError: The method '[]' was called on null."
"Receiver: null"
"Tried calling: [](0)"
I believe ['86400'.length - 1] is causing the error.
I have also tried using
var historicalPrice = decodedHistorical['result']['86400'][decodedHistorical.length - 1][0];
instead. This doesn't cause an error but it gives me the length of the outer array, which is 2 but I need the length of the inner array named '86400'.
You should implement below way
void parseJson() async {
http.Response historicalResponse = await http.get(historicalRequestURL);
Map decodedHistorical = jsonDecode(historicalResponse.body);
List selectedMap = decodedHistorical['result']['86400'];
var finalValue = selectedMap.last;
print(finalValue);
}
Instead of using var, use List so that you can access its last element by historicalPrice.last getter.
List historicalPrice = decodedHistorical['result']['86400'];
List lastElement=historicalPrice.last;
Related
I want to create a resource for many regions, environments, apps, etc at once.
I'd like to do something like this:
param apps array = [
'app1'
'app2'
'app3'
]
param environments array = [
'alpha'
'beta'
]
param regions array = [
'ne'
'we'
'uks'
]
resource origin_group 'Microsoft.Cdn/profiles/origingroups#2021-06-01' = [ for region in regions: {
[ for env in environments: {
[ for app in apps: {
parent: profiles_global_fd_name_resource
name: '${env}-${region}-${app}-origin-group'
properties: {
loadBalancingSettings: {
sampleSize: 4
successfulSamplesRequired: 3
additionalLatencyInMilliseconds: 50
}
healthProbeSettings: {
probePath: '/'
probeRequestType: 'HEAD'
probeProtocol: 'Http'
probeIntervalInSeconds: 100
}
sessionAffinityState: 'Disabled'
}
}]
}]
}]
All docs mentioning nested loops talk about looping inside a resource to create many sub-resources. Not what I'm after. Perhaps another way would be to somehow merge all these arrays into a single array of objects of every possible iteration. Not sure where to start with that either.
Any help much appreciated.
This is not supported for the moment but it will (see Is there plans to support nested loop on resources?).
Using a little bit of math, you could achieve what you'd like (Not sure if you should):
param environments array = [ 'alpha', 'beta' ]
param regions array = [ 'ne', 'we', 'uks' ]
param apps array = [ 'app1', 'app2', 'app3' ]
// Setting some variables for clarity
var envCount = length(environments)
var regionCount = length(regions)
var appCount = length(apps)
// Setting the total number of combination
var originGroupCount = envCount * regionCount * appCount
// Iterate all possible combinations
output originGroupNames array = [for i in range(0, originGroupCount): {
name: '${environments[i / (regionCount * appCount) % envCount]}-${regions[i / appCount % regionCount]}-${apps[i % appCount]}-origin-group'
}]
this will output all possible combinations (I think) for origin group name.
i would like to build a list of maps in terraform. Is there an operation that would let me do that.
eg: i would like to build the structure (from aws_instance.test.*.private_ip)
addresses = [
{
address = private_ip-1
},
{
address = private_ip-2
}
...
]
Apologies if this has already been resolved, I see that it's an older question.
I'm not sure if this is best practice, but this is the way I would attempt to reach the desired state.
Using the null_resource you'd be able to do the following:
variable "addresses" {
type = "list"
default = [
"private_ip-1",
"private_ip-2",
"private_ip-3"
]
}
resource "null_resource" "test" {
count = "${length(var.addresses)}"
triggers {
address = "${element(var.addresses, count.index)}"
}
}
output "addresses" {
value = "${null_resource.test.*.triggers}"
}
And have this output:
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
Outputs:
addresses = [
{
address = private_ip-1
},
{
address = private_ip-2
},
{
address = private_ip-3
}
]
I'm currently on terraform 0.11.5, null_resource appears to have been added in 0.6.7
There are limitations to the null_resource triggers though. interpolated variables can only result in strings. So, unfortunately you won't be able to interpolate a value that would result in a list or a map; for example:
resource "null_resource" "test" {
triggers {
mylist = "${var.addresses}"
}
}
will result in an error
Error: null_resource.test: triggers (address): '' expected type 'string', got unconvertible type '[]interface {}'
With terraform 10.8 you can
output "private_subnets" {
value = [
"${aws_subnet.private.*.id}"
]
}
https://github.com/hashicorp/terraform/issues/7430
Let's say I have this Json ..
{
"name": "Mark",
"gender": "male",
"account1": {
"accountNo": 1201,
"balance": 300
},
"account2": {
"accountNo": 1354,
"balance": 5000
}
}
What I expect is like ..
$scope.myArray = [
{
"accountNo": 1201,
"balance": 300
},
{
"accountNo": 1354,
"balance": 5000
}
];
In AngularJS, how can I pick some part of Json data and push it into an array iteratively( I mean, when I have account1, account2 account3 or more, it can still add them into the array).
You could normally just assign the array over, but in this scenario that is not an option because your array is psuedo.
Ideally you would like to be able to do what this answer (related question) does: How to return and array inside a JSON object in Angular.js which is simply
$scope.myArray = json.accounts;
However, as noted, you do not have an accounts array so you need to make one.
var accounts = [];
for(var key in json){
if( !json.hasOwnProperty(key) // skip prototype extensions
|| !json[key].hasOwnProperty("accountNo") //skip non account objects
) continue;
accounts.push(json[key]);
}
And now you may use this array
$scope.myArray = accounts;
You can access Json data like an array. Like var foo = { ... , 'bar' = 'value', ... } you could get foo value by doing this for['bar']. So, by knowing this, you simply do something like
var arr = [];
for (var i = 0; i < 10; i++) {
arr.push(foo['account'+i]);
}
Although, this has nothing to do with angularjs.
We have created an array of complextype(Carrier field) objects. See below metadata
{ shortName : 'Person',
namespace : 'Demo',
autoGeneratedKeyType : breeze.AutoGeneratedKeyType.Identity,
"dataProperties": [
{
"name": "carriers",
"complexTypeName":"Carrier:#Test",
"isScalar":false
}]
}
The Carrier entity is defined as below:
{
"shortName": "Carrier",
"namespace": "Test",
"isComplexType": true,
"dataProperties": [
{
"name": "Testing",
"isScalar":true,
"dataType": "String"
}
]
}
We have the following matching data for the above entities:
{
carriers: [
{
Testing : 'InputBox1'
},
{
Testing : 'InputBox2'
}
]
}
We are trying to dynamically add the complextype object(Carrier) to the above carriers array by using the following approach:
var test = {
"Testing" : "Test"
};
var result = manager.createEntity('Carrier', test);
The above code throws an exception(undefined is not a function) inside breeze.debug.js at line number 12457(see below code)
entity = entityType.createEntity(initialValues);
The exception is thrown since the complextype entity does not have 'createEntity' function in it.
What are we missing here?
Excellent question - Sorry I didn't have a chance to address this earlier.
When adding a complexType object you need to use the createInstance() method instead of the createEntity.
var thisEntityType = manager.metadataStore.getEntityType('Carrier');
var thisEntity = thisEntityType.createInstance(initialValues);
Basically you get the complexType and then create an instance of it using the values you want assigned. Keep in mind the initial values should be a hash object of course. Often I will include a helper function to do this for me like this -
function createComplexType(entityType, constructorProperties) {
var thisEntityType = manager.metadataStore.getEntityType(entityType);
var thisEntity = thisEntityType.createInstance(constructorProperties);
return thisEntity;
}
I have a schema like following : -
var P = {
s : [{
data : [],
sec : mongoose.Schema.Types.ObjectId
}]
};
Now I want to find only the object of section not entire the row. Like If I pass sec value I want only the value of s.data of that sec object.
example : -
{ s : [
{
data : [],
sec : '52b9830cadaa9d273200000d'
},{
data : [],
sec : '52b9830cadaa9d2732000005'
}
]
}
Result should be look like -
{
data : [],
sec : '52b9830cadaa9d2732000005'
}
I do not want all entire row. Is it possible? If yes, then please help me.
You can use the $elemMatch projection operator to limit an array field like s to a single, matched element, but you can't remove the s level of your document using find.
db.test.find({}, {_id: 0, s: {$elemMatch: {sec: '52b9830cadaa9d2732000005'}}})
outputs:
{
"s": [
{
"data": [ ],
"sec": "52b9830cadaa9d2732000005"
}
]
}
You can always get the value of some field by using find(). For example in your case:
db.collectionName.find({},{s.data:1})
So the first bracket is to apply any condition or query, and in the second bracket you have to define the field as 1(to fetch only those fields value).
Please check http://docs.mongodb.org/manual/reference/method/db.collection.find for more information.
Let me know if it solves your problem.
Not into Mongo or db but working with Pure JavaSript skills here is the Solution as you mentioned Node.js which would do the execution task of the below.
Schema
var P = { s : [
{
data : [],
sec : '52b9830cadaa9d273200000d'
},{
data : [],
sec : '52b9830cadaa9d2732000005'
}
]
};
Search Method Code
var search = function (search_sec){
for (var i=0; i<(P.s.length);i++){
var pointer = P.s[i].sec;
var dataRow = P.s[i];
if((pointer) === search_sec ){
console.log(dataRow);
}
}
};
Here is How you can call - search('search_id');
For example input :
search('52b9830cadaa9d2732000005');
Output:
[object Object] {
data: [],
sec: "52b9830cadaa9d2732000005"
}
Working Demo here - http://jsbin.com/UcobuVOf/1/watch?js,console