How do i compare an as3 string with a json array? - arrays

Im trying to compare two specific bits of information. One is in the form of a as3 string the other is in the form of a Json array.
The Json array shows customer data from a shop website. What i want to do is have as3 compare the string(i.e a customer name) with the data , and when it has found the matching name, only trace that customers specific information.
Im amusing id have to use a loop for the comparison , but im having trouble getting my head around how to convert the Json into specific junks that can then be compared individually with a string. Any help would be perfect.
Thanks

Be aware that JSON is just a standard AS3 object. There's no magic going on here; loop through it as you would any other structure and run your comparisons as usual.
Solution
var jsonObj:Object = {
"customers": [
{
"id": "04aa1ab3-521b-11e3-a29a-bc305bf5da20",
"name": "fake name",
"customer_code": "00000002",
"customer_group_id": "6012cd22-5166-11e3-a29a-bc305bf5da20",
"customer_group_name": "All Customers",
"first_name": "test",
"last_name": "test",
"company_name": "",
"email": "testest#yahoo.com"
}
]
}
var myString:String = "fake name";
for (var k:String in jsonObj.customers[0]) {
var v:String = jsonObj.customers[0][k];
if (v == myString) {
trace(myString + "'s email is " + jsonObj.customers[0].email)
}
}

Use a Dictionary Object to store customer objects using their unique names (or ids ) as reference;
You certainly do not want to write unnecessary loop search for a customer in question.
Solution.
var jsonObj:Object = {
"customers": [
{
"id": "04aa1ab3-521b-11e3-a29a-bc305bf5da20",
"name": "fake name",
"customer_code": "00000002",
"customer_group_id": "6012cd22-5166-11e3-a29a-bc305bf5da20",
"customer_group_name": "All Customers",
"first_name": "test",
"last_name": "test",
"company_name": "",
"email": "testest#yahoo.com"
}
]
}
//Dictionary Object to store customers
var customers:Dictionary=new Dictionary();
//customer object in the json
var customer:Object;
//loop json object to retrieve customers and
//store them in Dictionary using either unique name or id
for each(customer in jsonObj)
customers[customer.name]=customer;
//retrieve customer in question
function getCustomer(id:String):Object
{
return customers[id] as Object;
}

Related

Converting a typescript class object with dictionary to a JSON array

After some digging I decided my backend needed to consume duplicate keys and as a consequence my frontend can no longer send a dictionary as a JSON string.
See my previous question.
After applying the solution provided
let mediatagRequest = new MediaTagRequest(tags);
const headers = { 'content-type': 'application/json' }
let jsonObject = {};
for (let entry of mediatagRequest.tags.entries())
{
jsonObject[entry[0]] = entry[1];
}
const body = JSON.stringify({
tags: jsonObject
});
My current output (which is what I then wanted)
{
"tags": {
"city": "Karachi"
}
However my needs have changed and after a bit of of struggle I couldn't get my desired output to be like this
{
"tags": [
{
"key": "city",
"value": "Karachi"
},
{
"key": "city",
"value": "Mumbai"
}
]
}
Could someone help, thank you.
To get your desired output you could use the Object.entries() function to get the key, value pairs separately. This code segment will turn an object into a list of objects with key value pairs:
test_object = {
karachi: "dubai",
mumbao: "moscow",
};
output = Object.entries(test_object).map(([key, value]) => ({ key, value}));
console.log(output);
You can adapt this code to select the desired parts of your object and format them as you like. There are other Object functions you can see in the documentation.

Flutter : How to get value in Object JSON?

Good healty everyone, I want to ask something about managing data from JSON. I've JSON format like below :
{
"msg": "Success"
"data": [
{
"id": "1",
"notelp": "0000000000",
"user": "no1"
},
{
"id": "2",
"notelp": "1111111111",
"user": "no2"
},
],}
and I want to get value from variable "notelp", I expect output like this {"0000000000", "1111111111",} how to get it ?
I tried this before, but still can't get what I want,
if (response.statusCode == 200) {
final result = json.decode(response.body);
debugPrint('dataTelp: ${result['data']['notelp']}');
}
thank you guys to help me to solve it and stay save.
You can use the forEach or another looping method to get data from a list.
List outPut = [];
List data = response['data'];
data.forEach((element) {
outPut.add(element['notelp']);
});
print(outPut);

How to store maps to a firestore array

I have xyz document inside abc collection.
I want to add a map to an array inside document xyz.
I can add a single array item using this code
CollectionReference collection = this.collection(collection);
DocumentReference ref = collection.document(document);
ref.setData({"data": FieldValue.arrayUnion(values)});
here data is the parent array.
but when I try to add another map , firestore replace the values of index 0 , it does not add map to next index means to index 1,2,3 or .....
let see the example
here is the map
values = {
"tokens": "99",
"title": "Cleaning",
"location": {" lat": "34.4333", "lng": "53.4343"},
"id": "gVnGE5ZPRnQ8HYQq7dvT",
"client": "LFBXXj7Zi0xOr0FqBGID",
"date": "22/8/2019",
"message": "request message...",
"budget": "150",
"details": {
" When would you like to have the cleaners over?":
"week",
"What type of cleaning package would you prefer?":
"answer for the type of clean",
"Do you need the cleaning tools and materials?":
"false",
"What time do you prefer to have the cleaners over?":
"8/20/2019"
}
}
and I want to add it as new array item each time when I send data to the firestore
eg.
onTap() {
CollectionReference collection = this.collection(collection);
DocumentReference ref = collection.document(document);
ref.setData({"value": FieldValue.arrayUnion(values)});
}
here is the code
var values = {
"tokens": "99",
"title": "Cleaning",
"location": {" lat": "34.4333", "lng": "53.4343"},
"id": "gVnGE5ZPRnQ8HYQq7dvT",
"client": "LFBXXj7Zi0xOr0FqBGID",
"date": "22/8/2019",
"message": "request message...",
"budget": "150",
"details": {
" When would you like to have the cleaners over?":
"week",
"What type of cleaning package would you prefer?":
"answer for the type of clean",
"Do you need the cleaning tools and materials?":
"false",
"What time do you prefer to have the cleaners over?":
"8/20/2019"
}
}
onTap() {
CollectionReference collection = this.collection(collection);
DocumentReference ref = collection.document(document);
ref.setData({"value": FieldValue.arrayUnion(values)});
}
You are using setData function which overwrites your existing values. You need to use updateData function instead which will add the value to the existing array. Just change your onTap function to this:
onTap() {
CollectionReference collection = this.collection(collection);
DocumentReference ref = collection.document(document);
ref.updateData({"value": FieldValue.arrayUnion(values)});
}

Merge objects with different values using Angularjs or Underscore js

I'm trying to merge two objects into a single multidimensional object for use in Angularjs controller by the 'unique_id'. (Note I also have Underscore Js added in).
Object #1 example:
[
{ "unique_id": "001", "title": "Putting Green Challenge - Motion Depends on Force and Mass" },
{ "unique_id": "002", "title": "Molecules to Organisms: Frog Life Cycle" }
]
Object #2 example (has MANY more rows than object 1..):
[
{
"ab_id": "76153F02-29F3-11D8-95EA-951BF95D9AEF",
"unique_id": "001",
"title": "How Speed Relates to Energy",
"state": "NY",
"document_title": "Core Curriculum",
"grade_code": "K-4",
"grade_descr": "Elementary",
"state_id": "1.S2.3a",
"state_text": "Use appropriate \"inquiry and process skills\" to collect data"
},
{
"ab_id": "7980A762-29F3-11D8-BD14-861D7EA8D134",
"unique_id": "001",
"title": "How Speed Relates to Energy",
"state": "NY",
"document_title": "Core Curriculum",
"grade_code": "5-8",
"grade_descr": "Intermediate",
"state_id": "1.S3.2d",
"state_text": "formulate and defend explanations and conclusions as they relate to scientific phenomena"
}
]
My Controller:
abApp.controller("abEE", function(abService, $http, $scope, $q, _) {
var abApp = this;
$scope.abData = $http.get('/data/ab_activities.json', {
cache: false
});
$scope.eeData = $http.get('/activities/eedata', {
cache: false
});
$q.all([$scope.eeData, $scope.abData]).then(function(values) {
var val = ??? This is where I want to merge the objects into one big multidimensional object..
});
Here is the output of console.dir(values);
0 Object { data=[28], status=200, config={...}, more...}
1 Object { data=[743], status=200, config={...}, more...}
This is the desired output I'd like to try and get:
[
{ "unique_id": "001", "title": "Putting Green Challenge - Motion Depends on Force and Mass", "alignments": [{"ab_id": "76153F02-29F3-11D8-95EA-951BF95D9AEF","unique_id": "001","title": "How Speed Relates to Energy",...}, {"ab_id": "7980A762-29F3-11D8-BD14-861D7EA8D134", "unique_id": "001", "title": "How Speed Relates to Energy",...}]
]
Edit
after you updated the question, i created this plunker
hopes it's what you meant
To merge all objects by unique_id
var unions = {};
$q.all([$scope.eeData, $scope.abData]).then(function(values)
{
for (var i = 0; i< values.length; i++)
{
var value = values[i];
if (!unions[value.unique_id])
{
unions[value.unique_id] = {};
}
angular.extend(unions[value.unique_id], value);
}
});
// Do somthing with 'unions'
...
If you could switch to use lodash instead of underscore, it can be achieved like this:
var val = _.values(_.merge(_.indexBy(values[0].data, 'unique_id'), _.indexBy(values[1].data, 'unique_id')));
The underscore doesn't have _.merge(), you have to loop through each property without it.
I don't think angular or underscore have this kind of functionality. I would do something like the following pseudo-code:
tempObject = {}
for object in objectArray
if tempObject[object.unique_id] isnt undefined
tempObject[object.unique_id] = object
else angular.extend(tempObject[object.unique_id], object) // or the other way around depending on your preference
resultingArray = []
for object, key of tempObject
resultingArray.push(object)
You will have to run the for object in objectArray for both the returned arrays but that should work and is probably more efficient than most merge algorithms as at most it will loop through each returned arrays twice.

ExtJs root node

What is the root property value if I get a Json like that:
{
"status": {
"status": 0,
"msg": "Ok",
"protocolversion": "extjs.json"
},
"value": {
"table": [
[
"admin",
"Administrator",
""
],
[
"test",
"Test",
""
]
],
"total": 2
}
}
The data will be displayed in a gridpanel, 1 row is admin, 1 row is test, etc.
Tried:
value, value.table
How to get this to work?
value.table is correct for the root property, but you are using a json format that I don't think Ext is set up to handle by default. It has a reader for json that is used for an array of objects, not for an nested arrays of field values with no object mapping information.
If you have to use that format, you will either need to create your own readers/writers or just use Ext.Ajax.request(), and in the callback, parse the nested array into objects. Something like:
Ext.Ajax.request({
url: 'path.com/to/content',
success: function (response, operation) {
var data = Ext.JSON.decode(response.responseText);
var fields = data.value.table;
var records = [];
Ext.Array.each(fields, function (fieldArray, fieldIndex) {
Ext.Array.each(fieldArray, function(fieldValue, valueIndex) {
//Create record object if it doesn't exist
var record = records[valueIndex] || {};
//Create a switch statement based on the array index to set fields
switch(fieldIndex) {
case 0:
record.User_id = fieldValue;
break;
case 1:
record.Username = fieldValue;
break;
}
});
});
//Add the objects to the empty store
store.add(records);
}
});
That's not a production solution by any means since it doesn't handle that empty string at the end of your list or the case that you get a jagged array of arrays per field which I can't imagine what to do with. If it's within your control or influence, I would suggest using a format more like what Ext suggests so you can use the built in json proxy/reader/writer or go crazy with it and implement ext's remote procedure call format:
{
"success": true,
"message": "Success",
"data": [
{
"User_id": "admin",
"Username": "Administrator"
}, {
"User_id": "admin",
"Username": "Administrator"
}
]
}
In above example "value" is root property. But for JSON reader it's a property name (or a dot-separated list of property names if the root is nested).
so you can assign into your field you need following.
fields:['table.admin','table.test']

Resources