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
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'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'm reading back record sets in an express server using the node mssql package. Reading back the values outputs an array of Json objects as expected.
Now I need to modify the Email propoerty value of each Json object. So I tried looping through the recordset and changing the value at each index:
var request = new sql.Request(sql.globalConnection);
request.input('p_email', sql.VarChar(50), userEmail);
request.execute('GetDDMUserProfile', function(err, recordsets, returnValue) {
for (var i = 0; i < recordsets.length; i++){
recordsets[i].Email = "joe#gmail.com";
}
console.log(recordsets);
});
But instead of modifying the Emailvalue of each Json object, this code just appends a new email property to the last Json object.
How can you map new property values to an array of JSON objects?
Example output:
An example of the output is shown below, where a new Email property has been added to the end of the array instead of changing each existing property value:
[
[
{
ID:[
4
],
UserName:"Brian",
Email:"joe#gmail.com"
},
{
ID:[
5
],
UserName:"Brian",
Email:"joe#gmail.com"
}
Email:'joe#gmail.com' ]
]
The issue here is that your dataset appears to not be an array of JSON objects but, rather, an array of arrays of JSON objects. If you know for certain that you'll always have only one array in the top-most array, then you can solve the problem like this:
recordsets[0][i].Email = "joe#gmail.com";
to always target the first array in the top-most array. However, if the top-most array could potentially have more than one array, that'll be a different kind of issue to solve.
I'm trying to add a new item to whichever name that was passed in under whichever id. My first problem is that it seems like its not grabbing the values from any of my variables (name, item, id), instead just using them as object keys. My next issue is that when I tested by hard-coding sample table info onto here, it wasn't adding more items to that array, but simply replacing the entire array with whatever values I had here.
function addlist(name, item, id){ // Add to user's list
console.log(id);
db.collection('newcon').update({_id: id}, { "$set": { "$push": { name:item } } });
ret(id);
}
$set is not an array update operation.
The $set operator replaces the value of a field with the specified value.
You just want to use $push by itself, as in
.update({_id: id}, {$push: {name: item}})
You can't interpolate object property names in raw object declarations, so if you want to use a variable name you will have to create an object to do this:
var obj = {};
obj[name] = item;
You can then pass this to .update, {$push: obj}