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.
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 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);
I have array within the array and i want to delete particular JSON object by its value.
rows=[
[isTrue:'false',isAvailable:'false',name:'Abc',data:'ABC',Value:'ABC']
[isTrue:'false',isAvailable:'false',name:'Abc1',data:'ABC1',Value:'ABC1']
[isTrue:'false',isAvailable:'true',name:'Abc2',data:'ABC2',Value:'ABC2']
[isTrue:'false',isAvailable:'true',name:'Abc3',data:'ABC3',Value:'ABC3']
]
I want
rows=[
[name:'Abc',data:'ABC',Value:'ABC']
[name:'Abc1',data:'ABC1',Value:'ABC1']
[name:'Abc2',data:'ABC2',Value:'ABC2']
[name:'Abc3',data:'ABC3',Value:'ABC3']
]
I want to remove all the data which has boolean values present.
The example you have provided has array of objects (not array of array) and should the have following syntax -
rows=[
{isTrue:'false',isAvailable:'false',name:'Abc',data:'ABC',Value:'ABC'},
{isTrue:'false',isAvailable:'false',name:'Abc1',data:'ABC1',Value:'ABC1'},
{isTrue:'false',isAvailable:'true',name:'Abc2',data:'ABC2',Value:'ABC2'},
{isTrue:'false',isAvailable:'true',name:'Abc3',data:'ABC3',Value:'ABC3'}
]
So, you want to delete the key-value pairs from a JSON object which you can do using -
for (var row of rows) {
delete row['isTrue']; // this will delete the isTrue key from the object
delete row['isAvailable']; // this will delete the isAvailable key from the object
}
You can check the following link for other ways of deleting a key:
Remove a key from a javascript object
I've a REST api that returns the list of locales as dictionary:
{
"en-uk": "English UK",
"en-us": "English USA",
...
}
This dictionary is correctly ordered alphabetically by value.
When AngularJS receives it via HTTP, the dictionary gets automatically re-sorted by key, so when I bind to a select element the list of options is ordered by key, and the alphabetical order by key doesn't match the one by value, I get a wrong sorting.
The problem I suppose is due to the fact that such dictionary becomes basically one object with 800+ properties. How do I sort it by value?
First: You have to find all keys.
Second: Iterate all the keys.
Third: Then sort the array with values.
Please use the following:
let obj = {
"en-us": "English USA",
"en-uk": "English UK"
};
// Get an array of the keys:
let keys = Object.keys(obj);
// Then sort by using the keys to lookup the values in the original object:
keys.sort(function(a, b) { return obj[a] > obj[b] });
console.log(keys);
console.log(obj[keys[0]]);
You can modify the way you send the response from the server. Instead of sending the response as an object, send the stringified object.
The problem is indeed you cannot sort the values of the properties of an object. So I convert it to an array before binding it:
So,
languageResource.getCultures().then(function(cultures) {
vm.availableCultures = cultures;
});
becomes
languageResource.getCultures().then(function (culturesDictionary) {
var cultures = [];
angular.forEach(culturesDictionary, function (value, key) {
cultures.push({
lcid: key,
name: value
});
});
vm.availableCultures = cultures;
});
Seen this when the key is numerical. If the key's data type is string than it would keep its sorted state after an API call. If the key's data type is numerical, than, you would need set the key's value as a string and even add single quotes before and after the key's value, before the API sends it back.
I haven't tried the approach to stringfy the dictionary in the API. After the call you would parse the string back to an object with something like JSON.parse(string) might be your best bet.
I have an object myObj.employees which looks like this:
{"employees":[{"key":1419,"rankid":8,"label":"bob (47)","exclude":false,"color":"#ffffff","textColor":"#330000","active_events":[]},{"key":1420,"rankid":8,"label":"john (48)","exclude":false,"color":"#ffffff","textColor":"#330000","active_events":[]}]}
how do I add items to active_events for key = 1419 ?
Find the 1419 entry:
const entry = myObj.employees.find(obj => obj.key === 1419);
Add entries to active events:
entry.active_events.push("more item");
If you're working in Javascript you can use the .forEach function to iterate over the employees array in a brute force manner.
myObj.employees.forEach(function(e) {
if (e.key === 1419) {
e.active_events.push("waffles")
}
});
myObj.employees["employees"][0]["active_events"].append("new event")
unless the object you showed was really just myObj in which case the answer (in python) would be:
myObj["employees"][0]["active_events"].append("new event")
let's break this down.
We take your object (myObj.employees) which gives us a dictionary with one key value pair.
We dive into ["employees"] to access the employee list.
You want to edit the [0] index employee
You want to edit the ["active_events"] value
You want to append / edit the list. I think you can take it from here.
As others have show if you do not know the index of the employee you want to edit, which you probably won't, then you'll need to loop through and look for it.
for i, employee in enumerate(myObj["employees"]):
if employee["key"] == 1419:
myObj["employees"][i]["active_events"].append('new event')