How to store maps to a firestore array - arrays

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)});
}

Related

React - Update or Replace an Object with in the State object

I have an State varaible with array of objects like this.
type State = {
Dp: ArrayDataProvider<string, Message>;
};
Inside Dp i will have data which will hold the data in the form of array like this.
[{
"id": 1,
"name": "January",
"abc": abc,
"xyz": xyz
}, {
"id": 2,
"name": "February",
"abc": abc,
"xyz": xyz
}]
I want to replace the object which is having id 2 with the different object and i want to have my object like this .
[{
"id": 1,
"name": "January",
"abc": abc,
"xyz": xyz
}, {
"id": 2,
"name": "New month",
"abc": 1234abc,
"xyz": someVlaue
}]
how to do it in efficient way with typescript in react.
I have done something like this but not working
const data = this.state.Dp?.data.slice();
const index = data.findIndex(currentItem => {
return currentItem.id === updateData[0].id;
});
data[index] = updateData;
this.state.Dp.data = data;
this.setState({ Dp: this.state.Dp });
I use map to do this:
const data = this.state.Dp?.data.map(currentItem => {
return currentItem.id === updatedItem.id ? updatedItem : currentItem;
})
map creates a new array with the items from the previous array, but it gives you an opportunity to make adjustments to the items in the new array as it iterates through them. In my example, I'm checking the id of the item to see if it's the one you want to update, and swapping in your updatedItem if the ids match.
I'm not sure about the TypeScript part, to be honest. I haven't worked with it yet.
Note - I'm not sure what form your updateData is in, so you might have to adjust that. It seems like you want it to be an object, but in one of your lines you're treating it like an array.
Use findIndex to find index of the object where id is equal 2, then replace new object to that place.
let tempArray = [...array];
const index = tempArray.findIndex((element) => element.id === 2);
tempArray[index] = {
id: 2,
name: "New month",
abc: "1234abc",
xyz: "someVlaue"
};
setArray(tempArray);

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);

Angular Update value in localStorage

The problem I'm having, I can't add/change a given item inside a JSON object. I tried to convert it to use a simple put but that doesn't work since: Property "put" does not exist in type of "JSON"
Key: 123 Value:{"name":"123","email":"123","password":"123","country":"123","about":"123","image":""}
My method to change the country value.
newJson:JSON;
onSubmit(value:any){
this.newJson = JSON.parse(localStorage.getItem(this.id));
this.newJson.put("country", value.country);
localStorage.setItem(JSON.stringify(this.newJson));
}
The value I get from the parameter (the submitted value)
{"country":"Portugal"}
Try like this :
export class Component {
private jsonObj: any = {};
private key: string = "123";
constructor(){
this.jsonObj = {
"name": "123",
"email": "123",
"password": "123",
"country": "123",
"about": "123",
"image": ""
}
localStorage.setItem(this.key, JSON.stringify(this.jsonObj));
}
ngOnInit() {
let localStorageJsonData = JSON.parse(localStorage.getItem(this.key));
localStorageJsonData.country = "france";
localStorage.setItem("obj", JSON.stringify(localStorageJsonData));
console.log('localStorageJsonData', localStorageJsonData);
}
}

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

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;
}

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