How to properly store array inside of a Record - immutable.js

var z = Record({a: []});
var a = new z({a: [1]});
var b = new z({a: [1]});
expect(Immutable.is(a, b)).to.be.true; // false
This returns false because [] is a mutable structure. So I've changed that code into this:
var z = Record({a: List()});
var a = new z({a: List([1])});
var b = new z({a: List([1])});
expect(Immutable.is(a, b)).to.be.true; // true
And it seems to work since Immutable.List is immutable. So is this the properly way of storing an array inside of a Record?
Thank you!

`int A[] = new int[5];` //creates the "A" array with an integer datatype
`int B[] = new int[5];` //creates the "B" array with an integer datatype
Would be the correct syntax. You can drop the expect(Immutable.is(a, b)).to.be.true; // true
You are probably getting an error because there is no data type in the syntax you provided above.
Hope this helps.

Related

Convert and parse json string to key value pairs using NewtonSoft

Trying to convert a json string to key value pairs using Newtonsoft but no luck so far.
Response from the API:
var response = #"{'result':{'0199 - B344EE33':
{
'6400_00260100':{'1':[{'val':336688}]},
'6400_00462500':{'1':[{'val':null}]},
'6800_00832A00':{'1':[{'low':3000,'high':3000,'val':3000}]},
'6800_008AA200':{'1':[{'low':0,'high':null,'val':0}]}
}}}";
Result I want is a new object of key value pairs:
{
"6400_00260100" : 336688,
"6400_00462500" : null,
"6800_00832A00" : 3000,
"6800_008AA200" : 0
}
In the response the result will always be the first and only prop. In the next level the code 0199 - B344EE33 can change but there will be only one prop in this level so we can always take the first one. Then in the last level we always need the val property.
What I have is the following but for getting the key value pairs in a clean way I got stuck:
var json = JObject.Parse(response);
var result = json["result"].First;
var path = result.Path;
UPDATE
var jObjectResult = new JObject();
var response = #"{'result':{'0199 - B344EE33':
{
'6800_10821E00':{'1':[{'val':'SMA Sunny Boy'}]},
'6800_00A21E00':{'1':[{'val':'3.0.0.2222'}]},
'6800_00823400':{'1':[{'low':3000,'high':3000,'val':3000}]},
'6800_08822B00':{'1':[{'val':'SMA'}]},
'6800_08822000':{'1':[{'val':'Sunny Boy 3.0'}]}
}}}";
var json = JObject.Parse(response);
var json_serial = json["result"].First.Children<JObject>().ToList()[0];
foreach(var token in json_serial)
{
var tokenKey = token.Key;
var tokenVal = token.Value.SelectToken("$.1[0].val");
jObjectResult.Add(tokenKey, tokenVal);
}
You could use SelectTokens with the recursive descent operator .. to find all the val properties, then walk up the chain using .Parent repeatedly to get the corresponding key. Create new JProperties from this information and put them into a new JObject to get your result. Here is a "one-liner":
var result = new JObject(
JObject.Parse(response)
.SelectTokens("$..val")
.Select(jt => new JProperty(
((JProperty)jt.Parent.Parent.Parent.Parent.Parent.Parent).Name,
jt
))
);
Fiddle: https://dotnetfiddle.net/TbZ7LS
At the end with some pointers form #Brian Rogers I came with the following solution:
// Arrange
var response = #"{'result':{'0199 - B344EE33':
{
'6800_10821E00':{'1':[{'val':'SMA Sunny Boy'}]},
'6800_00A21E00':{'1':[{'val':'3.0.0.2222'}]},
'6800_00823400':{'1':[{'low':3000,'high':3000,'val':3000}]},
'6800_08822B00':{'1':[{'val':'SMA'}]},
'6800_08822000':{'1':[{'val':'Sunny Boy 3.0'}]}
}}}";
// Act
var json = JObject.Parse(response);
var json_serial = (JProperty)json["result"].First();
var jObjectResult = new JObject(
json_serial.Value.Select(p =>
{
return new JProperty(
((JProperty)p).Name,
p.First.SelectToken("$.1[0].val")
);
}));

How to get property from JSON model filled with oData?

Im trying to get property from oData return model. I set data in success callback function from oData to JSON model.
oODataModel.read("/ConnObjSet?$filter=Objecttype eq 'CONNOBJ' and ConnObject eq '20000000002'",
true,
true,
false,
function _OnSuccess(oData, oResponse){
var oJSON = new sap.ui.model.json.JSONModel();
oJSON.setData(oData);
sap.ui.getCore().setModel(oJSON, "ConnectionObject");
},
This is my JSON object in console log and highlighted property I want to get. I want to get every 15 Buspartner number from whole array.
And this is what I tried to get property:
var oLog = sap.ui.getCore().getModel("ConnectionObject").oData.results;
console.log(oLog);
If you have an array of objects, you can get an array of properties from each of these objects by using the Array.map() function.
So in your case:
var aResults = this.getView().getModel().getProperty("/results");
var aBuspartner = aResults.map(function (r) { return r.Buspartner});
var oJSONModel = new sap.ui.model.json.JSONModel();
oJSONModel.setProperty("/resultarray", aBuspartner)
Please try:
var aResults = this.getView().getModel().getProperty("/results");
var oJSONModel = new sap.ui.model.json.JSONModel();
oJSONModel.setProperty("/resultarray",new Array())
for(var i = 0; i<aResults.lenght;i++){
oJSONModel.getProperty("/resultarray").push(aResults[i].Buspartner)
}
You could also try to add a filter and select to your oData.read
The oData-URL
http://services.odata.org/V2/Northwind/Northwind.svc/Products
selects all Product with all their properties
http://services.odata.org/V2/Northwind/Northwind.svc/Products?$filter=UnitsInStock%20eq%2017
shows only Products with "UnitsInStock=17"
http://services.odata.org/V2/Northwind/Northwind.svc/Products?$select=ProductID&$filter=UnitsInStock%20eq%2017
selects only the ProductID of Products with "UnitsInStock=17"
so
oODataModel.read("/ConnObjSet?$select=Buspartner&$filter=Objecttype eq 'CONNOBJ' and ConnObject eq '20000000002'"
...
should get the filtered Buspartners directly.

Dealing with nested for loops in Swift for a JSON file

One of the JSON requests that I make returns a file with a bunch of nested information. The format is roughly as follows groups->individual group->teams in group.
Currently I am dealing with this with a nested for loop where I look at the outer groups and then run the inner loop to get the information for the individual teams.
I've uploaded a copy of the JSON file to paste bin, here is the link. http://pastebin.com/D14wYDEs. This particular example doesn't have that many groups and teams but its possible to have way more, which makes the concept of nested for loops seem impractical.
I was wondering if somebody had a suggestion as to a better system of doing this, or any suggestion really.
Heres my current code:
func generateTablaDePosiciones() {
estadisticaUtilizada = 3
var tablaDePosicionesJSON = getJSONStats(3,tkn,eqID)
//checks to see that contents != nil, meaning the JSON file was found
if tablaDePosicionesJSON != nil {
tablaDePosicionesArray.removeAll(keepCapacity: false)
var numeroDeGruposEnTablaDePosiciones = tablaDePosicionesJSON["grupos"].count
for var index = 0; index < numeroDeGruposEnTablaDePosiciones; ++index {
var grupo = tablaDePosicionesJSON["grupos"][index]["grupo"].string
var etiqueta1 = tablaDePosicionesJSON["grupos"][index]["etiqueta-1"].string
var etiqueta2 = tablaDePosicionesJSON["grupos"][index]["etiqueta-2"].string
var etiqueta3 = tablaDePosicionesJSON["grupos"][index]["etiqueta-3"].string
var etiqueta4 = tablaDePosicionesJSON["grupos"][index]["etiqueta-4"].string
var etiqueta5 = tablaDePosicionesJSON["grupos"][index]["etiqueta-5"].string
var preTablaDePosicionesNuevo = preTablaDePosiciones(grupo: grupo!, etiqueta1: etiqueta1!, etiqueta2: etiqueta2!, etiqueta3: etiqueta3!, etiqueta4: etiqueta4!, etiqueta5: etiqueta5!)
preTablaDePosicionesArray.append(preTablaDePosicionesNuevo)
numeroDeTablaDePosiciones = tablaDePosicionesJSON["grupos"][index]["lista-body"].count
for(var innerIndex = 0; innerIndex < numeroDeTablaDePosiciones; ++innerIndex) {
var rank = tablaDePosicionesJSON["grupos"][index]["lista-body"][innerIndex]["rank"].string
var equipoID = tablaDePosicionesJSON["grupos"][index]["lista-body"][innerIndex]["equipoID"].number! as Int
var nomEquipo = tablaDePosicionesJSON["grupos"][index]["lista-body"][innerIndex]["nom-equipo"].string
var d1 = tablaDePosicionesJSON["grupos"][index]["lista-body"][innerIndex]["d1"].string
var d2 = tablaDePosicionesJSON["grupos"][index]["lista-body"][innerIndex]["d2"].string
var d3 = tablaDePosicionesJSON["grupos"][index]["lista-body"][innerIndex]["d3"].string
var d4 = tablaDePosicionesJSON["grupos"][index]["lista-body"][innerIndex]["d4"].string
var d5 = tablaDePosicionesJSON["grupos"][index]["lista-body"][innerIndex]["d5"].string
var tablaDePosicionesNuevo = tablaDePosiciones(rank: rank!, equipoID: equipoID, nomEquipo: nomEquipo!, d1: d1!, d2: d2!, d3: d3!, d4: d4!, d5: d5!)
tablaDePosicionesArray.append(tablaDePosicionesNuevo)
}
}
} else {
estadisticaUtilizada = 0
println("Tabla de Posiciones JSON was nil")
}
}
I would use a while loop. Increment an index with each execution and then dynamically construct the key using that index. Collect your results in an array and then pass on that array instead of each individual object.
Also, you should really be unwrapping all these values as you're parsing them instead of force unwrapping (!). In this while loop you can use a conditional binding while let to handle that, and if it fails—i.e. it found no value for that key—it will exit.
Something like this:
var index = 1
var results = [String]()
while let etiqueta = grupo["etiqueta-\(index)"] as? String {
results.append( etiqueta )
index++
}
let preTablaDePosicionesNuevo = preTablaDePosiciones(grupo: name, etiquetas: results)
preTablaDePosicionesArray.append( preTablaDePosicionesNuevo )

actionscript arrays merge

I posted my problem a few hours ago, but I think I figured out how to ask my question in a more comprehensible way.
This is my code:
// 1. Intro
var introPL1:Array = ["intro1","intro2","intro3","intro4"];
var introPL2:Array = ["intro5","intro6","intro7","intro8","intro9"];
var introPL3:Array = ["intro10","intro11"];
var introPL4:Array = ["intro12","intro13"];
var allIntro:Array = [introPL1,introPL2,introPL3,introPL4];
// 2. Clothes
var clothesPL1:Array = ["clothes1","clothes2","clothes3","clothes4","clothes5"];
var clothesPL2:Array = ["clothes6","clothes7","clothes8"];
var clothesPL3:Array = ["clothes9","clothes10"];
var clothesPL4:Array = ["clothes11","clothes12","clothes13"];
var allClothes:Array = [clothesPL1,clothesPL2,clothesPL3,clothesPL4];
// 3. Colored Numbers
var colNumPL1:Array = ["colNum1","colNum2","colNum3","colNum4","colNum5"];
var colNumPL2:Array = ["colNum6","colNum7","colNum8"];
var colNumPL3:Array = ["colNum9","colNum10"];
var colNumPL4:Array = ["colNum11","colNum12","colNum13"];
var allColNum:Array = [colNumPL1,colNumPL2,colNumPL3,colNumPL4];
var allStuff:Array;
allStuff = allIntro.concat(allClothes, allColNum);
trace(allStuff[4]);
When I trace allStuff[4] it displays "clothes1,clothes2,clothes3,clothes4,clothes5".
The thing is, I would like all the stuff to be in the allStuff array (without sub-arrays) and when I trace allStuff[4], I would like it to display "intro5" (the fifth item in the huge allStuff array).
the function you want to use then is concat
here's the example from adobe
var numbers:Array = new Array(1, 2, 3);
var letters:Array = new Array("a", "b", "c");
var numbersAndLetters:Array = numbers.concat(letters);
var lettersAndNumbers:Array = letters.concat(numbers);
trace(numbers); // 1,2,3
trace(letters); // a,b,c
trace(numbersAndLetters); // 1,2,3,a,b,c
trace(lettersAndNumbers); // a,b,c,1,2,3
it's pretty straight forward:
allStuff= allStuff.concat(introPL1,introPL2,introPL3,introPL4,clothesPL1,clothesPL2,clothesPL3,clothesPL4,colNumPL1,colNumPL2,colNumPL3,colNumPL4);
you could also do a
allStuff = []
for each(var $string:String in $arr){
allStuff.push($string)
}
for each array, or make it into a function
Okay, once you have declared your arrays like so, you need an additional operation to flatten your arrays allClothes and so on. Do like this:
function flatten(a:Array):Array {
// returns an array that contains all the elements
// of parameter as a single array
var b:Array=[];
for (var i:int=0;i<a.length;i++) {
if (a[i] is Array) b=b.concat(flatten(a[i]));
else b.push(a[i]);
}
return b;
}
What does it do: The function makes an empty array first, then checks the parameter member by member, if the i'th member is an Array, it calls itself with that member as a parameter, and adds the result to its temporary array, otherwise it's just pushing next member of a into the temporary array. So, to make your allIntro a flat array, you call allIntro=flatten(allIntro) after declaring it as you did. The same for other arrays.

Push Object in AS3

I was wondering if it's possible to push values to an object like in Arrays:
array.push("value");
I wanna give each color a letter like a, b, c, ..
It should be like:
var colors = { "a" : "ffffff", "b" : "000000" };
How can I add now other colors with letters to this?
Simple as:
colors["c"] = "ff0000";
colors["d"] = "00ff00";
colors["e"] = "0000ff";
// etc
Hope that helps.
It's up to you to make a selection from an Object, a Dictionary or an Array. But if you want to use those "a","b","c" as keys you will want to use an Object or a Dictionary instance.
var colors:Object = {};
colors["a"] = "etc.";
colors["b"] = "etc.";
// or
var colors:Object = {};
colors.a = "etc.";
colors.b = "etc.";
// or
var colors:Object = {a:"etc.",b:"etc"};