If i find values in object i want to delete those values from array.
What would be the best solution to accompolished this task ?
ctrl.js
var selectedOwners = [];
$scope.deleteOwner = function(dataItem){
var workerKey;
var fullName;
angular.forEach(selectedOwners,function(val,index){
workerKey = val.workerKey;
fullName = val.fullName;
})
if(dataItem.workeyKey === workerKey || dataItem.fullName === fullName){
selectedOwners.splice(workerKey,fullName);
}
}
Array and Object
Array selectedOwners = [{"fullName":"Johnson, Rocio","workerKey":3506},{"fullName":"Johnson, John S.","workerKey":571},{"fullName":"Johnson, Camille A.","workerKey":1368}]
Object {
"workerKey": 3506,
"fullName": "Johnson, Rocio",
}
Should be as simple as this:
var selectedOwners = [{
"fullName": "Johnson, Rocio",
"workerKey": 3506
}, {
"fullName": "Johnson, John S.",
"workerKey": 571
}, {
"fullName": "Johnson, Camille A.",
"workerKey": 1368
}];
var obj = {
"workerKey": 3506,
"fullName": "Johnson, Rocio",
};
for (var i = 0; i < selectedOwners.length; i++) {
if (selectedOwners[i].workerKey === obj.workerKey) {
selectedOwners.splice(i, 1);
break;
}
}
Keep in mind the for loop assumes that the workerKey is unique in the array. That's is why we only need to compare on the workerKey property only and we also break out of the for loop after find a match.
Here's the loop if the workerKey is not unique:
for (var i = 0; i < selectedOwners.length; i++) {
if (selectedOwners[i].workerKey === obj.workerKey &&
selectedOwners[i].fullName === obj.fullName) {
selectedOwners.splice(i, 1);
// we need to decrement i by one because
// we just removed an element from the array
i--;
}
}
Use indexOf to get the position for the splice;
Since you're passing the object as dataItem you can do as follow:
$scope.deleteOwner = function(dataItem){
selectedOwners.splice(indexOf(dataItem), 1);
}
You could use lodash _.remove which is very simple
_.remove(selectedOwners , {
"fullName": "Johnson, Rocio",
"workerKey": 3506 //where condition
});
You might use grep function, like below:
$scope.deleteOwner = function(dataItem){
selectedOwners = $.grep(selectedOwners, function(value) {
return value.workerKey != dataItem.workerKey
&& value.fullName!= dataItem.fullName;
});
}
I think the best idea is to use just the filter array's method. No external JS dependencies.
var selectedOwners = [{"fullName":"Johnson, Rocio","workerKey":3506},{"fullName":"Johnson, John S.","workerKey":571},{"fullName":"Johnson, Camille A.","workerKey":1368}]
var item = {
"workerKey": 3506,
"fullName": "Johnson, Rocio",
}
var resultArray = selectedOwners.filter(function(i){
return !(i.fullname == item.fullname && i.workerKey == item.workerKey)
});
Related
I want to filter the multiple attributes with multiple values
'arr' is a list of all products and f_... is the attribute like color or type.
'namet' is the chosen attribute from the user.
'keyt' is the values of each attribute like red, yellow and green.
let arr = [
{ "id": 523, "f_105": ["992","996"], "f_104": ["985"], "f_106":["1000"] },
{ "id": 524, "f_105": ["993","996"], "f_104": ["984"], "f_106":["1001"] }
]
these arrays which user chose for searching
I can get the attrubites like this
var namet = ['f_106', 'f_106', 'f_105', 'f_105', 'f_104' ];
var keyt = ['1000' , '1001', '993', '996', '985'];
OR
var chooenKey = ['f_106', 'f_105', 'f_104']
var chosenAttr = {
"f_106": ["1000", "1001"],
"f_105": ["993", "996"],
"f_104": ["985"],
}
OR
var chosenAttr =
[
{"f_106": ["1000", "1001"]},
{"f_105": ["993", "996"]},
{"f_104": ["985"]}
]
I want a method to loop to get result like variable 'filtered'
var filtered = d =>
(d.f_106.indexOf("1000") > -1 || d.f_106.indexOf("1001") > -1) &&
(d.f_105.indexOf("993") > -1 || d.f_105.indexOf("996") > -1) &&
(d.f_104.indexOf("985") > -1)
then put it here
const f = arr.filter(filtered);
You can also give another type to filter the product with multiple attributes.
If you examine the example I sent, I believe it will solve your problem.
let arr = [
{ "id": 523, "f_105": ["992", "996"], "f_104": ["985"], "f_106": ["1000"] },
{ "id": 524, "f_105": ["993", "996"], "f_104": ["984"], "f_106": ["1001"] }
]
var chosenAttr =
[
{ "f_106": ["1000", "1001"] },
{ "f_105": ["992"] },
{ "f_104": ["985"] }
]
function filterArr() {
var arrCopy = arr;
for (i = 0; i < chosenAttr.length; i++) {
for (var key in chosenAttr[i]) {
arrCopy = arrCopy.filter(function (item) {
var is_match = false;
for (var idx in chosenAttr[i][key]) {
let val = chosenAttr[i][key][idx];
if (item[key].indexOf(val) > -1) {
is_match = true;
}
}
return is_match;
});
}
}
return arrCopy;
}
var filterData = filterArr();
$('#response').html(JSON.stringify(filterData));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<pre>
<code id="response">
</code>
</pre>
I'd like to convert this code:
for (var i = 0; i < product.ages.length; i ++){
for (var j = 0; j < $scope.ages.length; j ++){
if (product.ages[i].id == $scope.ages[j].id){
$scope.ages[j]['ticked'] = true;
}
}
}
into underscore.js. please help.
Another way to solve this problem would be to first create a hash of the scope.ages using underscore's indexBy:
var scope_ages = _.indexBy($scope.ages, 'id');
The object would look something like:
{
1: ref to scope.ages with id 1,
2: ref to scope.ages with id 2,
etc.
}
Then iterate over the product ages using each to set the ticked value:
_.each(product.ages, age => scope_ages[age.id].ticked = true)
var product = {
ages: [
{ id : 1 }
]
}
var $scope = {
ages: [
{ id : 0, ticked: false },
{ id : 1, ticked: false },
{ id : 2, ticked: false },
]
}
var scope_ages = _.indexBy($scope.ages, 'id');
_.each(product.ages, age => scope_ages[age.id].ticked = true)
document.getElementById('scope_ages').textContent = JSON.stringify(scope_ages);
document.getElementById('result').textContent = JSON.stringify($scope.ages);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore.js"></script>
<h1>scope_ages</h1>
<p>
<pre id="scope_ages"></pre>
</p>
<h1>Scope</h1>
<p>
<pre id="result"></pre>
</p>
This would be your code in underscore:
_.each(product.ages, function(pAge) {
_.each($scope.ages, function(sAge) {
if (pAge.id === sAge.id) {
sAge.ticked = true;
}
});
});
Here is an example on how you do an _.each on an object.
var example = {"hello":"world", "this":"is", "super":"neat"};
_.each(example, function(value, index){
console.log(index + ":" + value);
}
->hello:world
->this:is
->super:neat
You can use _.find
_.each($scope.ages, function(v){
v.ticked = _.find(product.ages, function(a){
return v.age === a.age;
})?true:false;
})
Also, just a pointer, you should use break on match.
I have got sample json object has format like this below ..
var result = [{"value":"S900_Aru","family":"S400"},
{"value":"S500_Aru","family":"S400"},
{"value":"2610_H","family":"A650"}]
if you see first two values are related to same family and the third one is belongs to other family ...
How can i loop through this complete json object and i need to alert the customer saying that these three are not related to same family ...
Would any one please help on this issue..
Many thanks in advance
You could just use Array.prototype.every():
var test = result.every(function(item, index, array){
return item.family === array[0].family;
}); // true if all items in array have same family property set
var result = [{"value":"S900_Aru","family":"S400"},
{"value":"S500_Aru","family":"S400"},
{"value":"2610_H","family":"A650"}];
var test = result.every(function(item, index, array){
return item.family === array[0].family;
});
alert(test);
A simple loop with comparisons will do.
for (var i= 1, first = result[0].family; i< result.length; i++) {
if (result[i].family !== first) {
alert('Family mismatch')
}
}
You can try something like
var jsonString = '[{"value":"S900_Aru","family":"S400"},{"value":"S500_Aru","family":"S400"},{"value":"2610_H","family":"A650"}]';
var jsonData = $.parseJSON(jsonString);
var valueArray = new Array();
$.each(jsonData, function (index, value) {
valueArray.push(value['value']);
if ($.inArray(value['value'], valueArray)) {
alert('Duplicate Item');
return;
} else {
// Continue
}
});
I will store the first value of family and use every to check for every elements of the array.
value = result[0].family;
function isSameFamily(element) {
return element.family == value;
}
a = result.every(isSameFamily);
https://jsfiddle.net/ejd64es0/
if(a){
alert("Same family")
}
else{
alert("Not Same family")
}
You can use two for loops to check each object with each other object and log the message when two families don't match.
for(var i=0;i<result.length-1;i++) {
for(var j=1;j<result.length;j++) {
if(result[i].family !== result[j].family)
console.log("Families do not match");
}
}
var result = [{"value":"S900_Aru","family":"S400"},
{"value":"S500_Aru","family":"S400"},
{"value":"2610_H","family":"A650"}]
var itemFamily = result[0].family;
var differs = false;
result.forEach(function(itm){
if (itemFamily != itm.family) {
differs = true;
}
});
alert((differs)?"Not related to the same family":"Related to the same family");
You can check every element with the first element and return the result of Array#every().
var result = [{ "value": "S900_Aru", "family": "S400" }, { "value": "S500_Aru", "family": "S400" }, { "value": "2610_H", "family": "A650" }],
related = result.every(function (a, i, aa) {
return aa[0] === a;
});
document.write(related);
I have some JSON-code which has multiple objects in it:
[
{
"MNGR_NAME": "Mark",
"MGR_ID": "M44",
"EMP_ID": "1849"
},
{
"MNGR_NAME": "Steve",
"PROJ_ID": "88421",
"PROJ_NAME": "ABC",
"PROJ_ALLOC_NO": "49"
}
]
My JSON loop snippet is:
function ServiceSucceeded(result)
{
for(var x=0; x<result.length; x++)
{
}
}
Could you please let me know how to check there is no occurence of "MNGR_NAME" in the array. (It appears twice in my case.)
You need to access the result object on iteration.
for (var key in result)
{
if (result.hasOwnProperty(key))
{
// here you have access to
var MNGR_NAME = result[key].MNGR_NAME;
var MGR_ID = result[key].MGR_ID;
}
}
You could use jQuery's $.each:
var exists = false;
$.each(arr, function(index, obj){
if(typeof(obj.MNGR_NAME) !== 'undefined'){
exists = true;
return false;
}
});
alert('Does a manager exists? ' + exists);
Returning false will break the each, so when one manager is encountered, the iteration will stop.
Note that your object is an array of JavaScript objects.
Could you use something like this?
var array = [{
"MNGR_NAME": "Mark",
"MGR_ID": "M44",
"EMP_ID": "1849"
},
{
"MNGR_NAME": "Steve",
"PROJ_ID": "88421",
"PROJ_NAME": "ABC",
"PROJ_ALLOC_NO": "49"
}];
var numberOfMngrName = 0;
for(var i=0;i<array.length;i++){
if(array[i].MNGR_NAME != null){
numberOfMngrName++;
}
}
console.log(numberOfMngrName);
This will find the number of occurrences of the MNGR_NAME key in your Object Array:
var numMngrName = 0;
$.each(json, function () {
// 'this' is the Object you are iterating over
if (this.MNGR_NAME !== undefined) {
numMngrName++;
}
});
Within the loop result[x] is the object, so if you wanted to count a member that may or may not be present;
function ServiceSucceeded(result)
{
var managers = 0
for(var x=0; x<result.length; x++)
{
if (typeof result[x].MNGR_NAME !== "undefined")
managers++;
}
alert(managers);
}
You can iterate over the collection and check each object if it contains the property:
var count = 0;
var i;
for(i = 0; i < jsonObj.length; i += 1) {
if(jsonObj[i]["MNGR_NAME"]) {
count++;
}
}
Working example: http://jsfiddle.net/j3fbQ/
You could use $.each or $.grep, if you also want to get the elements that contain the attribute.
filtered = $.grep(result, function(value) {
return (value["MNGR_NAME"] !== undefined)
});
count = filtered.length
Use ES6...
myobj1.map(items =>
{
if(items.MNGR_NAME) {
return items.MNGR_NAME;
}else {
//do want you want.
}
})
Thanks.
Say I have this JSON:
[
{
"ID": "1",
"title": "Title 1",
},
{
"ID": "2",
"title": "Title 2",
}
]
How would I return the set of key names that recur for each record? In this case, ID, title.
I tried:
$.getJSON('testing.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push(key +', ');
});
$('<p/>', {
html: items.join('')
}).appendTo('#content');
});
without success.
This is a JSON "database", and every "record" has the same keys. I just want a script that will tell me what the keys are, not test whether or not they occur in every entry.
This will give you an array of all the string properties that match across an array of objects. Is that what you are looking for?
$.getJSON('testing.json', function(data) {
var propertiesThatExistInAll = getPropertiesThatExistInAll(data);
});
var getPropertiesThatExistInAll = function(arr) {
var properties = $.map(data[0], function (prop, value) {
return prop;
});
var propertiesThatExistInAll = [];
$.each(properties, function (index, property) {
var keyExistsInAll = true;
// skip the first one since we know it has all the properties
for (var i = 1, len = data.length; i < len; i++) {
if (!data[i].hasOwnProperty(property)) {
keyExistsInAll = false;
break;
}
}
if (keyExistsInAll) {
propertiesThatExistInAll.push(property);
}
});
return propertiesThatExistInAll;
};
Something like this, perhaps?
items = [];
for (key in jsonobj) {
if (!itemExists(items, key)) {
items[items.length] = key
}
}
function itemExists(items, value) {
for (i = 0; i < items.length; i++) {
if (items[i] == value) {
return true
}
}
return false;
}
Of course, that will return items that exist in any one of the objects, not that exist in all. It's not entirely clear from your question if this is the solution you want.
This can probably be made more efficient/concise, but the function below will do it.
var testJson = [ {'oi' : 1, 'arf': 2, 'foo' : 0}, {'oi': 5, 'arf': 7}];
function commonKeys(j)
{
var fillUp = [];
for(var i in j[0])
fillUp.push(i);
for(var i = 1; i < j.length; i++)
{
var cur = j[i]; var curArr = [];
for (var i in cur) {curArr.push(i)};
fillUp = fillUp.filter(function(x) {return (curArr.indexOf(x) != -1);});
}
return fillUp;
}
alert(commonKeys(testJson)); //oi,arf (not foo)