json comparison with in the object - javascript

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

Related

Removing an item from a two dimensional Javascript Array

I have a simple array like this:
var CutRoadArray = [
['Location', '_Location'],
['Applicant Info', '_ApplicantInfo'],
['Details', '_ApplicationDetails'],
['Bond Info', '_BondInfo'],
['Attachments', '_Attachments'],
['Review', '_ReviewA']
];
I would like to check if this array contains the entry
['Bond Info', '_BondInfo'],
And if it does, remove it. In a separate scenario, I would like to search for the same, and if it doesnt exist, add it at a certain index.
I have tried various ways, none worked. Any help will be much appreciated.
One of the ways I have tried to accomplish this is:
Array.prototype.remove = function () {
var what, a = arguments, L = a.length, ax;
while (L && this.length) {
what = a[--L];
while ((ax = this.indexOf(what)) !== -1) {
this.splice(ax, 1);
}
}
return this;
};
function indexOfRowContainingId(id, matrix) {
var arr = matrix.filter(function (el) {
return !!~el.indexOf(id);
});
return arr;
}
Then calling something like:
var bond = indexOfRowContainingId('_BondInfo', CutRoadArray);
if (bond.length > 0) {
var ar = CutRoadArray.remove("['Bond Info', '_BondInfo']");
console.log(ar);
}
Try this:
var CutRoadArray = [
['Location', '_Location'],
['Applicant Info', '_ApplicantInfo'],
['Details', '_ApplicationDetails'],
['Bond Info', '_BondInfo'],
['Attachments', '_Attachments'],
['Review', '_ReviewA']
];
var testElem = ['Bond Info', '_BondInfo'];
for(var i=0; i<CutRoadArray.length; i++){
var temp = CutRoadArray[i].toString();
if(temp === testElem.toString()){
//remove element from array
CutRoadArray.splice(i, 1);
break;
}
}
console.log(CutRoadArray);
This function has your desired functionality:
function testArray(test, array){
return array.filter(function(x){
return x.toString() != test;
})
}
testArray(['Bond Info', '_BondInfo'], CutRoadArray)

get specific text from value with javascript

I have a json.json file like this
{
"name1":"ts1=Hallo&ts2=Hillarry&ts3=Sting&ts4=Storm",
"name2":"st1=Hallo2&st2=Hillarry2&st3=Sting2&st4=Storm2",
"name3":"dr1=Hallo3&dr2=Hillarry3&dr3=Sting3&dr4=Storm3",
"name4":"ds1=Hallo4&ds2=Hillarry4&ds3=Sting4&ds4=Storm4"
}
And this script im using to read the file
<script type='text/javascript'>
$(window).load(function(){
$.getJSON("json.json", function(person){
document.write(person.name3);
});
});
</script>
This script is made to point out all of the data from "name3" but i need only "dr3" value from "name3" to be stored to be written.
How to do that?
You can store it like this using combination of split() calls.
var dr3val = person.name3.split("&")[2].split("=")[1];
console.log(dr3val); // "Sting3"
The above will work if the order is same. Else you can use the below
var dr3val = person.name3.replace(/.*?dr3=(.+)?&.*/,"$1");
console.log(dr3val); // "Sting3"
You should change your json to this:
{
"name1":
{
"ts1" : "Hallo",
"ts2" : "Hillarry",
"ts3" : "Sting",
"ts4" : "Storm"
}
}
this way it makes your jsonstring much easier to use.
Get the data from it like this:
person.name1.ts1
var json = {
"name1":"ts1=Hallo&ts2=Hillarry&ts3=Sting&ts4=Storm",
"name2":"st1=Hallo2&st2=Hillarry2&st3=Sting2&st4=Storm2",
"name3":"dr1=Hallo3&dr2=Hillarry3&dr3=Sting3&dr4=Storm3",
"name4":"ds1=Hallo4&ds2=Hillarry4&ds3=Sting4&ds4=Storm4"
};
var name3 = json.name3.split('&');
for (var i = 0; i < name3.length; i++) {
if (name3[i].indexOf("dr3=") > -1) {
var value = name3[i].replace("dr3=", "");
alert(value);
}
}
Implement this jQuery plugin i made for a similar case i had to solve some time ago. This plugin has the benefit that it handles multiple occurring variables and gathers them within an array, simulating a webserver behaviour.
<script type='text/javascript'>
(function($) {
$.StringParams = function(string) {
if (string == "") return {};
var result = {},
matches = string.split('&');
for(var i = 0, pair, key, value; i < matches.length; i++) {
pair = matches[i].split('=');
key = pair[0];
if(pair.length == 2) {
value = decodeURIComponent(pair[1].replace(/\+/g, " "));
} else {
value = null;
}
switch($.type(result[key])) {
case 'undefined':
result[key] = value;
break;
case 'array':
result[key].push(value);
break;
default:
result[key] = [result[key], value];
}
}
return result;
}
})(jQuery);
</script>
Then in your code do:
<script type='text/javascript'>
$(window).load(function(){
var attributes3;
$.getJSON("json.json", function(person){
attributes3 = $.StringParams(person.name3)
console.log(attributes3.dr3);
});
});
</script>
Underscore solution:
_.map(json, function(query) { //map the value of each property in json object
return _.object( //to an object created from array
query.split('&') //resulting from splitting the query at &
.map(function(keyval) { //and turning each of the key=value parts
return keyval.split('='); //into a 2-element array split at the equals.
);
})
The result of the query.split... part is
[ [ 'ts1', 'Hallo'], ['ts2', 'Hillarry'], ... ]
Underscore's _.object function turns that into
{ ts1: 'Hallo', ts2: 'Hillarry', ... }
The end result is
{
name1: { ts1: 'hHallo', ts2: 'Hillarry, ...},
name2: { ...
}
Now result can be obtained with object.name3.dr3.
Avoiding Underscore
However, if you hate Underscore or don't want to use it, what it's doing with _.map and _.object is not hard to replicate, and could be a useful learning exercise. Both use the useful Array#reduce function.
function object_map(object, fn) {
return Object.keys(object).reduce(function(result, key) {
result[key] = fn(object[key]);
return result;
}, {});
}
function object_from_keyvals(keyvals) {
return keyvals.reduce(function(result, v) {
result[v[0]] = v[1];
return result;
}, {});
}
:
var person={
"name1":"ts1=Hallo&ts2=Hillarry&ts3=Sting&ts4=Storm",
"name2":"st1=Hallo2&st2=Hillarry2&st3=Sting2&st4=Storm2",
"name3":"dr1=Hallo3&dr2=Hillarry3&dr3=Sting3&dr4=Storm3",
"name4":"ds1=Hallo4&ds2=Hillarry4&ds3=Sting4&ds4=Storm4"
}
var pN = person.name3;
var toSearch = 'dr3';
var ar = pN.split('&');
var result = '';
for(var i=0; i< ar.length; i++)
if(ar[i].indexOf(toSearch) >= 0 )
result=ar[i].split('=')[1];
console.log('result=='+result);

JSON data group by

I have json data which contain the whole database record now i need to perform group by on this return json data with sorting on particular category.
I think sorting is easy to do on json data but i am not sure how i can go with group by. I need to group by on particular set of data.
Any help/suggestion would be great help.
Thanks
ravi
var obj = [{ "session":"1","page":"a"},
{ "session":"1","page":"b"},
{ "session":"1","page":"c"},
{ "session":"2","page":"d"},
{ "session":"2","page":"f"},
{ "session":"3","page":"a"}];
function GroupBy(myjson,attr){
var sum ={};
myjson.forEach( function(obj){
if ( typeof sum[obj[attr]] == 'undefined') {
sum[obj[attr]] = 1;
}
else {
sum[obj[attr]]++;
}
});
return sum;
}
var result = GroupBy(obj,"page");
console.log("GroupBy:"+ JSON.stringify(result));
/// GroupBy(obj,"session") --> GroupBy:{"1":3,"2":2,"3":1}
/// GroupBy(obj,"page") --> GroupBy:{"a":2,"b":1,"c":1,"d":1,"f":1}
Check the http://linqjs.codeplex.com or http://jslinq.codeplex.com. It's javascript libraries that mimics LINQ. Here is other questions like yours:Javascript Dynamic Grouping
var obj = [{Poz:'F1',Cap:10},{Poz:'F1',Cap:5},{Poz:'F1',Cap:5},{Poz:'F2',Cap:20},{Poz:'F1',Cap:5},{Poz:'F1',Cap:15},{Poz:'F2',Cap:5},{Poz:'F3',Cap:5},{Poz:'F4',Cap:5},{Poz:'F1',Cap:5}];
Array.prototype.sumUnic = function(name, sumName){
var returnArr = [];
var obj = this;
for(var x = 0; x<obj.length; x++){
if((function(source){
if(returnArr.length == 0){
return true;
}else{
var isThere = [];
for(var y = 0; y<returnArr.length; y++){
if(returnArr[y][name] == source[name]){
returnArr[y][sumName] = parseInt(returnArr[y][sumName]) + parseInt(source[sumName]);
return false;
}else{
isThere.push(source);
}
}
if(isThere.length>0)returnArr.push(source);
return false;
}
})(obj[x])){
returnArr.push(obj[x]);
}
}
return returnArr;
}
obj.sumUnic('Poz','Cap');
// return "[{"Poz":"F1","Cap":45},{"Poz":"F2","Cap":25},{"Poz":"F3","Cap":5},{"Poz":"F4","Cap":5}]"

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.

Test existence of JSON value in JavaScript Array

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

Categories

Resources