Test existence of JSON value in JavaScript Array - javascript

I have an array of JSON objects like so:
var myArray = [
{name:'foo',number:2},
{name:'bar',number:9},
{etc.}
]
How do I detect if myArray contains an object with name="foo"?

Unless I'm missing something, you should use each at the very least for readability instead of map. And for performance, you should break the each once you've found what you're looking for, no reason to keep looping:
var hasFoo = false;
$.each(myArray, function(i,obj) {
if (obj.name === 'foo') { hasFoo = true; return false;}
});

With this:
$.each(myArray, function(i, obj){
if(obj.name =='foo')
alert("Index "+i + " has foo");
});
Cheers

for(var i = 0; i < myArray.length; i++) {
if (myArray[i].name == 'foo')
alert('success!')
}

var hasFoo = false;
$.map(myArray, function(v) {
if (v.name === 'foo') { hasFoo = true; }
});

Related

How to put a condition in jQuery's map function?

I am trying to put a condition in jQuery's map function. My issue is that I don't want the same number in the map function value. When it is the same I want to display an alert box. My map function code is like this:
var rankbox= $('input[type=text][class = cate_rank]').map(function() {
return this.value;
}).get();
If I get a value like 1,2,3,4,5 it's ok, but if I get a value like 1,2,3,2,5, I want to display an alert box. Is it possible?
How to put a condition in jQuery's map function?
function change_rank() {
var rankbox= $('input[type=text][class = cate_rank]').map(function() {
if() {
} else { }
return this.value;
}).get();
var vals = []
$('input[type=text][class = cate_rank]').each(function(){
if($(this).val() && (typeof vals[$(this).val()] == 'undefined')){
vals[$(this).val()] = 1;
var last_val = $(this).val();
}else if($(this).val() && (typeof last_val != 'undefined') && parseInt(last_val) > parseInt($(this).val())){
alert('Whooah! Something went terribly wrong! Inputs don\'t have values ordered incrementally!');
}else{
alert('Whooah! Something went wrong! We got two inputes with same value!');
}
});
Check this,
var rankbox= $(".test").map(function() {
return this.value;
}).get();
var sorted_arr = rankbox.slice().sort();
var results = [];
for (var i = 0; i < rankbox.length - 1; i++) {
if (sorted_arr[i + 1] == sorted_arr[i]) {
results.push(sorted_arr[i]);
}
}
var rankbox= $(".test").map(function() {
if($.inArray(this.value, results) > -1){
alert(this.value+" is duplicate");
}
return this.value;
}).get();
I took reference of this link
If you are Looking to check dup you can try this:
var x=[1,2,3,2,5]
var has=!x.every(function(v,i) {
return x.indexOf(v) == i;
});
console.log(has);//true means dup found else not found.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
you can try with a object. check this:
function change_rank() {
var temp = {};
var rankbox= $('input[type=text][class = cate_rank]').map(function() {
if(temp[this.value]==undefined) {
temp[this.value] = this.value;
} else {
alert('the same value');
}
return this.value;
}).get();

json comparison with in the object

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);

Javascript - Remove duplicates value in array

But I want to leave last two duplicated value in array just like
arr = [1,2,3,4,4,4,4,4,5,6,6,6]
and the result will be
result = [1,2,3,4,4,5,6,6]
The reason why I want to leave last two is I have 2 arrays like date and data and it must match with each other.
Thank you.
Using jquery you can use:
var newarr=[];
$.each(arr, function(i, e) {
if ($.inArray(e, newarr) == -1) newarr.push(e);
});
console.log(newarr)
Try this:
var arr = [1,2,3,4,4,4,4,4,5,6,6,6],
result = [],
fisrtOccurence = -1;
for(var i=0; i<arr.length; i++) {
fisrtOccurence = result.indexOf(arr[i]);
if(fisrtOccurence === -1) {
result.push(arr[i]);
} else {
if(result.indexOf(arr[i],fisrtOccurence+1) === -1) {
result.push(arr[i]);
}
}
}
console.log(result);
Try this solution : JSFiddle
var arr = [1,2,3,4,4,4,4,4,5,6,6,6]
// using reduce function of array
Array.prototype.unique = function() {
return this.reduce(function(previousValue, current) {
if (previousValue.indexOf(current) < 0) {
previousValue.push(current);
}
return previousValue;
}, []);
}
console.log(arr.unique());
// using filter
var filteredArray= arr.filter(function(element, index, self) {
return index == self.indexOf(element);
});
console.log(filteredArray);
Demo
Try this
newarr = [];
testarr = [];
duplicatearr = [];
locArray = [1,2,3,4,4,4,4,4,5,6,6,6];
for (var i = 0; i<locArray.length;i++)
{
var idx = $.inArray(locArray[i], testarr);
if (idx == -1) {
testarr.push(locArray[i]);
newarr.push(locArray[i]);
}
else
{
var id = $.inArray(locArray[i], duplicatearr);
if (id == -1) {
newarr.push(locArray[i]);
duplicatearr.push(locArray[i]);
}
}
}
console.log(newarr);

Dynamically building array, appending values

i have a bunch of options in this select, each with values like:
context|cow
context|test
thing|1
thing|5
thing|27
context|beans
while looping through the options, I want to build an array that checks to see if keys exist, and if they don't they make the key then append the value. then the next loop through, if the key exists, add the next value, comma separated.
the ideal output would be:
arr['context'] = 'cow,test,beans';
arr['thing'] = '1,5,27';
here's what i have so far, but this isn't a good strategy to build the values..
function sift(select) {
vals = [];
$.each(select.options, function() {
var valArr = this.value.split('|');
var key = valArr[0];
var val = valArr[1];
if (typeof vals[key] === 'undefined') {
vals[key] = [];
}
vals[key].push(val);
});
console.log(vals);
}
Existing code works by changing
vals=[];
To
vals={};
http://jsfiddle.net/BrxuM/
function sift(select) {
var vals = {};//notice I made an object, not an array, this is to create an associative array
$.each(select.options, function() {
var valArr = this.value.split('|');
if (typeof vals[valArr[0]] === 'undefined') {
vals[valArr[0]] = '';
} else {
vals[valArr[0]] += ',';
}
vals[valArr[0]] += valArr[1];
});
}
Here is a demo: http://jsfiddle.net/jasper/xtfm2/1/
How about an extensible, reusable, encapsulated solution:
function MyOptions()
{
var _optionNames = [];
var _optionValues = [];
function _add(name, value)
{
var nameIndex = _optionNames.indexOf(name);
if (nameIndex < 0)
{
_optionNames.push(name);
var newValues = [];
newValues.push(value);
_optionValues.push(newValues);
}
else
{
var values = _optionValues[nameIndex];
values.push(value);
_optionValues[nameIndex] = values;
}
};
function _values(name)
{
var nameIndex = _optionNames.indexOf(name);
if (nameIndex < 0)
{
return [];
}
else
{
return _optionValues[nameIndex];
}
};
var public =
{
add: _add,
values: _values
};
return public;
}
usage:
var myOptions = MyOptions();
myOptions.add("context", "cow");
myOptions.add("context","test");
myOptions.add("thing","1");
myOptions.add("thing","5");
myOptions.add("thing","27");
myOptions.add("context","beans");
console.log(myOptions.values("context").join(","));
console.log(myOptions.values("thing").join(","));
working example: http://jsfiddle.net/Zjamy/
I guess this works, but if someone could optimize it, I'd love to see.
function updateSiftUrl(select) { var
vals = {};
$.each(select.options, function() {
var valArr = this.value.split('|');
var key = valArr[0];
var val = valArr[1];
if (typeof vals[key] === 'undefined') {
vals[key] = val;
return;
}
vals[key] = vals[key] +','+ val;
});
console.log(vals);
}
Would something like this work for you?
$("select#yourselect").change(function(){
var optionArray =
$(":selected", $(this)).map(function(){
return $(this).val();
}).get().join(", ");
});
If you've selected 3 options, optionArray should contain something like option1, option2, option3.
Well, you don't want vals[key] to be an array - you want it to be a string. so try doing
if (typeof vals[key] === 'undefined') {
vals[key] = ';
}
vals[key] = vals[key] + ',' + val;

How to loop through JSON array?

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.

Categories

Resources