Trying to merge two arrays with some simmilar occurances in two array
here's what i did
var json_dest = [
{
"legID":"12121",
"message":212112
},
{
"legID":"12122",
"message":212112
}
];
var json_src = [
{
"legID":"12121",
"message":212100
},
{
"legID":"12123",
"message":212112
}
];
console.log(angular.merge(json_dest, json_src));
the output is:
[
{
"legID":"12121",
"message":212100
},
{
"legID":"12123",
"message":212112
}
]
it merged the duplicates
but i am missing the other legID "12123"
i need to know how it can be done efficiently ?
and also why is it happening ?
angular.merge is not used to merge arrays but to deeply extend the destination object with enumerable properties of the source object:
Deeply extends the destination object dst by copying own enumerable properties from the src object(s) to dst. You can specify multiple src objects. If you want to preserve original objects, you can do so by passing an empty object as the target:
var object = angular.merge({}, object1, object2) Source
If you just want to combine the two arrays into one you don't need an angular API to do that. Simply use concat:
json_dest = json_dest.concat(json_src);
If you want to remove the duplicates by a certain property, for example legID in your case, you can do that after combining the arrays. There are plenty of resources on how to do that. See for example this question: Remove duplicates from an array of objects in javascript
syntax for merge is
var object = angular.merge({}, obj1, obj2);
it is showing only second element
try using
console.log(angular.merge(dst, src1, src2));
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'm currently working on a function which generates an mongodb modifier object based on an orginal object and an changed object.
The goal is to update the document as carefully as possible. (only changes will be added to the modifier)
Changed objects (which may be nested) work just fine. But I'm having issues with arrays:
If I take an array [1,2,3,4] and run arr.splice(1,1), the array looks like this: [1,3,4]. This is correct.
The problem is the following:
When I compare [1,2,3,4] to [1,3,4] my function would change the indexes 1 and 2 and then remove the 3rd index since its not needed anymore.
The generated modifier would look like this:
//document in collection
{
arr: [1,2,3,4]
}
//generated modifier
{
$set: {
'arr.1': 3,
'arr.2': 4
},
$push: {
$slice: 3
}
}
This produces the following error:
MongoError: Cannot update 'arr.1' and 'arr' at the same time
Do you have any suggestions how to remove this last index within one query?
Or do I have to use multiple updates to archive this?
I merge two arrays in my AngularJS controller and sent it via http.post:
var selectedIds = angular.extend({}, $scope.selectedFirstKeys, $scope.selectedSecondKeys);
$http.post("/api/tests/test/1", selectedIds )
.then(function (response) {
...
});
With Fiddler I see the array is sent like this:
{"0":22}
But when I define my POST method like this it doesn't recognize the array:
[HttpPost("test/{testId:long}")]
public IActionResult Test(long testId, [FromBody] long[] selectedIds)
{
...
}
How do I define the Controller method so it recognizes the array?
Taking into consideration that what you want to pass to your backend logic is an array.
This code is wrong
var selectedIds = angular.extend({}, $scope.selectedFirstKeys, $scope.selectedSecondKeys);
Because: it copies the content of $scope.selectedFirstKeys, and $scope.selectedSecondKeys into {} (which is an object!), so the final result will be an object too! :(
The correct way (Assuming that $scope.selectedSecondKeys and $scope.selectedSecondKeys are arrays) is:
$scope.selectedFirstKeys = $scope.selectedFirstKeys.concat($scope.selectedSecondKeys);
Because: it set $scope.selectedFirstKeys with the result of cancatenating $scope.selectedFirstKeys and $scope.selectedSecondKeys, which will be an array too! :)
You might want to see additional info about Array.prototype.concat (and on SO) and angular.extend (and on SO). An extract is shown below:
Array.prototype.concat
The concat() method returns a new array comprised of the array on
which it is called joined with the array(s) and/or value(s) provided
as arguments.
Syntax
var new_array = old_array.concat(value1[, value2[, ...[, valueN]]])
Parameters
valueN: Arrays and/or values to concatenate into a new array.
angular.extend
Extends the destination object dst by copying own enumerable
properties from the src object(s) to dst.
Syntax
angular.extend(dst, src);
Parameters
dst: Destination object
src: Source object(s)
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 currently have a observable array of objects which inside of those have observable properties.
appViewModel.diceArray = ko.observableArray( [ {
diceAmount: ko.observable(1),
diceType: ko.observable(null),
diceAddition: ko.observable(0),
diceMultiplication: ko.observable(1)
} ] );
I am now looking to save the data to a database, and so need my array of objects (without them being observable). Is there a quicker method than looping through the array and manually creating objects?
Use ko.toJS
From http://knockoutjs.com/documentation/json-data.html
ko.toJS — this clones your view model’s object graph, substituting for each observable the current value of that observable, so you get a plain copy that contains only your data and no Knockout-related artifacts
If the potatopeelings' answer is not what you want. You can use the ko.utilsArrayMap:
var dices = ko.utils.arrayMap(appViewModel.diceArray, function(dice) {
return { diceAmount: dice.diceAmount(),
diceType: dice.diceType(),
diceAddition: dice.diceAddition(),
diceMultiplication: dice.diceMultiplication()
}
});
//do something with dices
ko.toJS is also available as an industrial strength mapping plugin which also supports going the other way, which you are going to need.