I don't understand something and need explanations please !
I have a datatable and selection of lines generate in my .ts an array of Operation object. here is my object class :
export class Operation {
id: number;
name: string;
}
this is the declaration of array :
selectedOperations: Operation[];
when I log in console before extraction of ids, I have this :
this.selectedOperations = {"selected":[{"id":1,"name":"My name 1"},{"id":3,"name":"My name 3"}]}
and when I want to extract ids with this :
let ids = this.selectedOperations.map(o => o.id);
I have an exception =>
this.selectedOperations.map is not a function
It's not the first time I have this problem and I'd like to understand why. I search some reasons and found differences between Array and object[] ? I think it's not really an array because there is the {"selected": before the array...
Can someone tell me the thing and help me for extract ids ?
thanks a lot !
{"selected":[{"id":1,"name":"My name 1"},{"id":3,"name":"My name 3"}]} => this is of type object, whereas your array declaration looks like this selectedOperations: Operation[];
You either directly assign the array to your variable:
this.selectedOperations = [{"id":1,"name":"My name 1"},{"id":3,"name":"My name 3"}];
Or you can change your variable type to any or object:
selectedOperations: any;
this.selectedOperations = {"selected":[{"id":1,"name":"My name 1"},{"id":3,"name":"My name 3"}]}
const ids = this.selectedOperations.selected.map(o => o.id);
this.selectedOperations.map is not a function error is caused by the initialization, map function is reserved for arrays, therefore it throws an error when you try to use it on an object type variable.
I would recommend the first approach by the way, declaring a variable as any or object is contradicting with the purpose of Typescript.
You need to make some improvements to the code. In order to get the ids, you need to add selected to this.selectedOperations. See below.
let ids = this.selectedOperations.selected.map(o => o.id);
Related
I have a mongoose object which contains an array of ObjectIds, being used for population from another table. I want to be able to dedupe these. eg I have
[ '61e34f3293d9361bbb5883c7' ,'61e34f3293d9361bbb5883c7', '61e34f3293d9361bbb5883c7' ]
When i print and iterate through these they look like strings.
But they also have an _id property, so I think they're somehow "populated" or at least contain references to the child table.
What's the best way to do this? I tried:
const uniqueTokens = _.uniqBy(tokens, '_id') which doesn't seem to work as _id is some kind of Object.
converting to a string will allow me to dedupe:
const tokens = this.tokens || []
let newTokens: string[] = []
for (let t of tokens) {
const text = t.toString()
// clog.info('t', t, t._id, typeof t._id)
if (!newTokens.includes(text)) {
newTokens.push(text)
}
}
but then these aren't real Objects I can assign back to the original parent object.
// this.tokens = newTokens
await this.save()
I could maybe go through and re-find the objects, but that seems to be digging deeper into the hole!
Seems there must be a better way to handle these type of types...
related searches
How to compare mongoDB ObjectIds & remove duplicates in an array of documents using node.js?
I also tried using lean() on the tokens array to try and convert it back to a simple list of references, in case somehow the 'population' could be undone to help.
I'm down to creating a unique signature field for the referenced items and de-duping based on that.
I have an address that looks like this
let address = [{"_id":"6013a6ef20f06428741cf53c","address01":"123","address02":"512","postcode":"23","state":"512","country":"32","key":1},{"_id":"6013a6eh6012428741cf53c","address01":"512","address02":"6","postcode":"6612","state":"33","country":"512","key":2}]
How can I remove '_id' and 'key' together with its Key and Value Pair.
And can you please let me know how does this type of array is called? Is it called Object in Array? I keep seeing this type of array but I have no clue how to deal with this, is there like a cheatsheet to deal with?
You can access the property of the object like this:
address[0]["_id"]
// or
address[0]._id
and you can delete the property like this:
delete address[0]["_id"]
// or
delete address[0]._id
Where 0 is the 1st index of the array. You might need to iterate over your array and remove the property from each object:
address.forEach(a => {
delete a._id;
delete a.key;
});
First, this type of array is called "Array of Objects" (objects inside array)
Second, you can generate new set of array by delete the key which you want to remove by,
let newSetOfArray = address.map((obj)=> {
delete obj._id;
delete obj.key;
return obj;
});
console.log(newSetOfArray); // this array of objects has keys with absence of _id & key.
I have a response from the server that looks like this
[
{
"metric":{
"id":"b66178b8-dc18-11e8-9f8b-f2801f1b9fd1",
"name":"Detector de fum bucatarie",
"metricValueType":"DOUBLE",
"metricType":"DEVICE_VALUE",
"groupUUID":null,
"projectUUID":null,
"companyUUID":"ccab28ed-3dcf-411f-8748-ec7740ae559c",
"unit":null,
"formula":null
},
"data":{
"1550150771819":"10.310835857351371"
}
}
]
Data property contains a hashMap with Timestamp and a Value.
When I try to get any value I recive this error:
myErrorTypeError: undefined is not an object (evaluating 'metricValues.metric.id')
How can I access a property ? I tried both methods :
metricValues.metric.id
and
metricValues["metric"]["id"]
How can I get the hashMap values?
I already tried this :
const timestamp = Object.keys(metricValues.data)[0];
const values = Object.values(metricValues.data)[0];
Your data is an array of objects. So even though your data has only one object, still it is an array of objects.
your object is at index 0 of the array.
You can access the metric Id as follows,
metricValues[0].metric.id
Try This (put that [0])
metricValues[0].metric.id
Your response from the server is an array. And the metric object is in the first element of that array.
To access the id inside the metric object you need to pass the index at which that object is present in the array which is 0 here.
That's why use :
metricValues[0].metric.id
I'm trying to run a simple query, where I search for a document that contains a value inside an object array.
For instance, look at my database structure:
I want to run a query similar to this:
db.collection('identites').where("partyMembers", "array-contains", {name: "John Travolta"})
What is the correct way to achieve this, is it even possible with Firestore?
Thanks.
As Frank has explained in his answer it is not possible, with array-contains, to query for a specific property of an object stored in an array.
However, there is a possible workaround: it is actually possible to query for the entire object, as follows, in your case:
db.collection('identites')
.where(
"partyMembers",
"array-contains",
{id: "7LNK....", name: "John Travolta"}
)
Maybe this approach will suit your needs (or maybe not....).
The array-contains operations checks if an array, contains a specific (complete) value. It can't check if an array of objects, contains an item with a specific value for a property.
The only way to do your query, is to add an additional field to your document with just the value you want to query existence on. So for example: partyMemberNames: ["John Travolta", "Olivia Newton"].
If you want to extract name: "John Travolta" from "partyMembers" array in a document. you can achieve this by some similar approach in which you can loop through all arrays in a document to find this name.
const [names, setNames] = React.useState([])
const readAllNames = async() => {
const snapshot = await firebase.firestore().collection('identites').doc(documentID).get()
const filterData = snapshot.data().question.map(val => val.name === "John Travolta" ? val : null)
setNames( filterData.filter(e=>e) );
}
This technique is used in perticular Document as we are giving .doc(documentID) This way you can get all the arrays having name: "John Travolta" in names constant.
I have the prerequisite setup...
define([ "dojo/_base/array", array ...
I create my array "concats" in the "return declare([], { concats: [], ..." area. There is a method/function called _createForm: function (fields) { ...}
Inside of this function I have : this.concats = [];
Inside of _createForm is a call to another method/function called : _createFormElement and inside of there whenever I try to PUSH to this.concats I get
"TypeError: Cannot read property 'push' of undefined"
I've tried every conceivable method to add items to this array but nothing I do, short of including this.concats = [] in the _createFormElement function will let me. AND if I include this.concats = [] in the _createFormElement function then it erases the array...
So sure, it holds ONE object, but I need it to collect objects for each Form Field in a global-ish array.
I'm so confused.
So it turns out I just have to reference the "global" (but not really global) array variable like so in my _createFormElement function/method...
var myVariable = this.concats;
Then in that function I can push like so...
myVariable.push(itemToPush);