angularjs add item to object array - arrays

I have a set of array and object that look like this
`
var PaymentContent = "Payments":
[{
"Details": {
"PaymentType": "CreditCard",
"Amount": $scope.total,
"CCNAME": $scope.Form.CreditCard.FullName,
}
}]
Payments: Array[1]
0:Object
Details: Object
Amount: 5.99
CCNAME: null
PaymentType: "CreditCard"`
Now, how can i update that set of objects and array using angularjs?
desired output :
Payments: Array[1]
0:Object
Details: Object
Amount: 5.99
CCNAME: null
PaymentType: "CreditCard"
LastPayment: "04/11/2011"
Notice the lastpayment field.
Here is my code
var paymentDetails = {LastPayment : '04/11/2011', LastSignOn : '04/11/2011'}
fields = angular.extend({}, PaymentContent , paymentDetails);
Thanks!

You are setting an empty object as destination. This new object will receive the properties and values of the other 2 objects...without changing those other 2 source objects
If you want the array object to receive the updates remove the first argument ( the empty object)
angular.extend( fields.Payments[0].Details, paymentDetails);
This will update fields.Payments[0].Details with all of the properties and values in paymentDetails
Demo Fiddle

You can directly write below code:
Payments[0].LastPayment = "04/11/2011";

Related

react js lodash loop thru and change a field value

I am new at reactjs and lodash. I have an array of objects which each has many field properties. I want to change a name string value if the boolean property is true. I read thru some of the posts here, seem like .map will loop thru the array
const updatedList = this.props.oldList.map((record) => record.IsTrue === 1 ? `$({record.name} (Updated)` : record.name)
I ran the test and it did not worked at all. Instead of returning list of object with all its properities, I got the following
0: "Test1 (Updated)"
1: "Test2"
There is not object with field names and values. I was expecting the following
[
{name: "Test1 (Updated)", IsTrue: 1},
{name: "Test1", IsTrue: 0}
]
Any help with lodash is appreciated.
You can use spread syntax to return the other key and value and update the name-value where isTrue is 1.
const input = [{ name: "Test1", IsTrue: 1 }, { name: "Test1", IsTrue: 0 }],
output = input.map((record) => ({
...record,
name: record.IsTrue === 1 ? `${record.name} (Updated)` : record.name
}));
console.log(output);

filter items from an array of javascript objects

I have a map of the form,
var map1 = {123 : true, 345: false, 456:true} ; where 123, 345, 456 are ids with status 'true' or 'false'.
Now, based on the boolean status of the ids above, I need to remove the records of those ids from the below array,
[ {
id:123,
name:'foo'
},
{
id:345,
name:'baar'
},{
id:456,
name:'foobar'
}]
So, in this example, the objects with ids '121' and '456' should be deleted as they are with boolean status 'true' in the map.
Given that your map is called map1 and your array you need to filter is called arr this should do the trick:
arr.filter((elem) => { return !map1[elem.id] }

Elasticsearch query parse failure

Why does this ES multi-match query return a 400 error (bad request)?
"query": {
"multi_match": {
"query": searchTerms,
"fields": ["content", "title"],
"operator": "and"
}
},
size: 100,
from: 0,
highlight: {
fields: {
"title": {number_of_fragments: 0},
"content": {number_of_fragments: 10,fragment_size: 300}
}
}
}
I'm using this query in conjunction with AngularJS UI Bootstrap Typeahead code like this
uib-typeahead="query as query._source.ymme for query in getSuggestions($viewValue)" typeahead-on-select="search($item)"
This is my search() function
$scope.search = function() {
console.log($scope.searchTerms);
$scope.currentPage = 0;
$scope.results.documents = [];
$scope.isSearching = true;
return searchService.search($scope.searchTerms, $scope.currentPage).then(function(es_return) {
var totalItems = es_return.hits.total;
var totalTime = es_return.took;
var numPages = Math.ceil(es_return.hits.total / $scope.itemsPerPage);
$scope.results.pagination = [];
for (var i = 1; i <= 100; i++) {
if(totalItems > 0)
$scope.results.totalItems = totalItems;
$scope.results.queryTime = totalTime;
$scope.results.pagination = searchService.formatResults(es_return.hits.hits);
$scope.results.documents = $scope.results.pagination.slice($scope.currentPage, $scope.itemsPerPage);
}
}
),
function(error){
console.log('ERROR: ', error.message);
$scope.isSearching = false;
}
};
I'm not quite sure what is wrong? I'm thinking it has something to do with $scope, but I'm not sure. The query works when I use it Sense plugin for ES and it also works if I just type in a search term instead of selecting it from the autocomplete dropdown.
If it is $scope, what am I missing?
UPDATE
All shards failed for phase: [query_fetch]
org.elasticsearch.search.SearchParseException: [hugetestindex][0]: from[-1],size[-1]: Parse Failure [Failed to parse source [{"query":{"multi_match":{"query":{"_index":"hugetestindex","_type":"doc","_id":"57","_score":3.877801,"_source":{"ymme":"bourne supremacy"}},"fields":["content","title"],"operator":"and"}},"size":100,"from":0,"highlight":{"fields":{"title":{"number_of_fragments":0},"content":{"number_of_fragments":10,"fragment_size":300}}}}]]
UPDATE 2 Object {_index: "hugetestindex", _type: "doc", _id: "56", _score: 2.5276248, _source: Object}
I think that is the problem, instead of a search terms, its receiving "Object"....?
UPDATE 3So basically it goes like this,
[Object, Object, Object, Object, Object]
0: Object
_id: "229"
_index: "hugetestindex"
_score: 3.3071127
_source: Object
ymme: "bourne supremacy"
__proto__: Object
_type: "doc"
__proto__:
Object1:
Object2:
Object3:
Object4:
Object
length: 5
__proto__: Array[0]
where "bourne supremacy" is the value of the ymme field in the _source Object, the array at the top with the 5 objects is the es return, es_return.hits.hits - this last hits, is the array.
The way you deconstruct your object is by doing something like the following:
object.data.hits.hits._source.field_name;
The above is only a notation to get the value of a single field, you might need to do a loop for each of those values so maybe something like:
$scope.list = []
for hit in object.data.hits.hits {
$scope.list.push(hit._source.field);
}
console.log(list);
Then from your HTML you want to use this list by doing an ng-repeat with it or something similar to get each of the terms in the list.
<div ng-repeat="term in list">{{term}}</div>
If you can update your question with how your object looks and what data you want from it, I can update this answer to match it exactly.
UPDATE
To match your data structure, I'm assuming you want to extract each of the ymme values from those objects. You need to do the following:
<div ng-repeat="object in es_return.hits.hits">
{{object._source.ymme}}
</div>
Just make sure "es_return" is a $scope variable so you can access it as above or just do:
$scope.es_return = es_return;
In your Angular code

AngularJS filter by id returns multiple entrys

i had an array like this:
arr = [
{ID: 502, Description: 'aaa', code: 1122},
{ID: 2, Description: 'bbb', code: 2211},
{ID: 700, Description: 'ccc', code: 2222}
];
when i try to filter the ID I get all occurences of the specific number:
$(filter)('filter')( arr, { ID: 2 } )[0]
returns entry one ID: 502 but it should return the entry with ID: 2
Where is my fault?
According to the docs when used with an object it will match the element if it contains the value.
A pattern object can be used to filter specific properties on objects contained by array. For example {name:"M", phone:"1"} predicate will return an array of items which have property name containing "M" and property phone containing "1".
There is a second option comparator passing true will cause it to perform a strict equality meaning it should only return exact matches.
$filter('filter')( arr, { ID: 2 }, true);
Fiddle: https://jsfiddle.net/enxbpjg0/
You could use a function instead of the object. So...
$filter('filter')(arr, function(value) {
return value.ID === 2;
});

adding new object inside of array of objects in react

I am having a little problem when trying to add a new object to an array of objects which is stored in state.
Below is a example of the object which is stored in state (scratchTickers):
id : uuid.v1(),
area : 'Scratch',
name : 'Untitled',
status : "",
size : "",
created : {
name : "username",
time : new Date()
},
modified : {
name : "username",
time : new Date()
},
content: [{
content: "Dummy content",
TowerRed: "",
TowerText: "Headlines"
}]
I need to dynamically add new objects in the content array, an object is structured like this:
{
content: "Dummy content",
TowerRed: "",
TowerText: "Headlines"
}
I am trying to use React's immutability helpers to accomplish this but It doesn't seem to be working as it should.
here is my function to add a new object to the content array and update the state:
_createTickerItem: function (id) {
var tickerID = id;
var key = null;
for (var i = 0; i < this.state.scratchTickers.length; i++) {
if(this.state.scratchTickers[i].id == tickerID) {
var ticker = this.state.scratchTickers[i];
var key = i;
}
}
var blankContent = ({
content: "Ticker Content",
TowerRed: "",
TowerText: "Headlines"
});
var oldContent = this.state.scratchTickers[key];
var newContent = update(oldContent, {
content : {
$push : [blankContent]
}
});
this.setState({
scratchTickers: newContent
});
},
So when i clicl the button tun run the _createTickerItem function the component re-renders and the main object has disappeared entirely.
Edit* Ok so I am now 1 step further making sure to set 'newContent' as an array during set state now adds new objects to the content array and renders them correctly.
this.setState({
scratchTickers: [newContent]
});
However if there were multiple objects in state, this will replace them all with juts a single object. So how would it work if I had say to parent objects in state but wanted to just modify the content array of object 1?
Edit 2: i should add that scratchTickers is an array of objects, so the for loop is needed to make sure i modify the correct object.
You're replacing the entire scratchTickers array with only the last updated object.
You have to update the entire array first.
var updates = {};
updates[key] = { $set: newContent }
var newScratchTickers = update(this.state.scratchTickers, updates);
this.setState({
scratchTickers: newScratchTickers
});

Resources