how to count similar value object in json? - javascript

I have this JSON structure:
[{
"name": "ankit",
"DOB": "23/06"
}, {
"name": "kapil",
"DOB": "26/06"
}, {
"name": "ankit",
"DOB": "27/06"
}]
I want to count similar object with value ankit. How can I do this?

You can use Array.prototype.filter():
var count = json.filter(function (el) {
return el.name == 'ankit';
}).length;

How about:
let a = [
{ "name": "ankit", "DOB": "23/06" },
{ "name": "kapil", "DOB": "26/06" },
{ "name": "ankit", "DOB": "27/06" }
];
let count = 0;
a.forEach(item => {
if (item.name === "ankit") {
count++;
}
});
(code in playground)

You could use an object for counting and get the wanted count for a name with the name as property.
var data = [{ "name": "ankit", "DOB": "23/06" }, { "name": "kapil", "DOB": "26/06" }, { "name": "ankit", "DOB": "27/06" }],
count = {};
data.forEach(function (a) {
count[a.name] = (count[a.name] || 0) + 1;
});
console.log(count);
console.log(count['ankit']);

You can use the reduce method to reduce the items that have the name ankit to a number.
var items = [
{
name: 'ankit',
DOB: '23/06'
},
{
name: 'kapil',
DOB: '26/06'
},
{
name: 'ankit',
DOB: '27/06'
}
]
var numItems = items.reduce(function (count, item) {
return item.name === 'ankit' ? count + 1 : count
}, 0)
document.write('Number of items with the name `ankit`: ' + numItems)

1. Get the object from JSON:
var obj = JSON.parse(text);
2. Get your array filtered:
var count = obj.filter(function(obj) { return obj.name == "ankit" }).length;

Related

Common objects in two objects

This function returns diff between two objects , i need to modify it to return common objects. Any help is appreciated.
Array sample:
var array1 = [{
"Name": "Single",
"URL": "xxx",
"ID": 123
}, {
"Name": "Double",
"URL": "yyy",
"ID": 888
}, {
"Name": "Triple",
"URL": "zzz",
"ID": 567
}];
var arrar2 = [{
"Name": "Single",
"URL": "xxx",
"ID": 123
}, {
"Name": "Double",
"URL": "yyy",
"ID": 888
}, {
"Name": "index",
"URL": "zzz",
"ID": 567
}];
// expected result
var resultArray = [{
"Name": "Single",
"URL": "xxx",
"ID": 123
}, {
"Name": "Double",
"URL": "yyy",
"ID": 888
},
}];
Current code:
function objDiff(array1, array2) {
var resultArray = []
array2.forEach(function(destObj) {
var check = array1.some(function(origObj) {
if (origObj.name == destObj.name) return true
})
if (!check) {
destObj.desc = 'missing in source'
resultArray.push(destObj)
}
})
array1.forEach(function(origObj) {
var check = array2.some(function(destObj) {
if (origObj.name == destObj.name) return true
})
if (!check) {
origObj.desc = 'missing in destination'
resultArray.push(origObj)
}
})
return resultArray
}
If all you want is to look for things that are the same in both arrays, you only need to loop over one of them. Something along these lines should work:
function objSame(array1, array2) {
var resultArray = []
array2.forEach(function(destObj) {
var check = array1.some(function(origObj) {
if(origObj.name == destObj.name) return true
})
if(check) {
destObj.desc = 'Same in both'
resultArray.push(destObj)
}
})
return resultArray
}
To find array elements that have a common Name property value, you could use a Map to avoid O(n²) time complexity. That map would have the objects from the first array keyed by their name. Pass it as the this object to a filter on the second array:
function objCommon(array1, array2) {
return array2.filter(function (obj) {
return this.has(obj.Name);
}, new Map(array1.map(obj => [obj.Name, obj])));
}
var array1= [
{ "Name": "Single", "URL": "xxx", "ID": 123 },
{ "Name": "Double", "URL": "yyy", "ID": 888},
{ "Name": "Triple", "URL": "zzz", "ID": 567 }];
var array2= [
{ "Name": "Single", "URL": "xxx", "ID": 123 },
{ "Name": "Double", "URL": "yyy", "ID": 888 },
{ "Name": "index", "URL": "zzz", "ID": 567 }];
var result = objCommon(array1, array2);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
That's not your code, but the following function will return all matches by exploring both arrays with two forEach() loops. Algorithm complexity is given by array1.length * array2.length. Don't use for large arrays! But it's the easiest way to think of it. Indeed the first think that comes to my mind is checking every element of array2 for every element of array1 and compare them.
var array1 = ['DETE', 'Ivany', 'James', 'Don', 'Crakcer']
var array2 = ['Jamies', 'Ivanyy', 'DETE', 'Don']
function objMatch(array1,array2) {
var matches = [];
array1.forEach(function(element1) {
array2.forEach(function(element2) {
if(element1 == element2) {
matches.push(element1);
}
});
});
return matches;
}
console.log(objMatch(array1, array2));
// will return ['DETE', 'Don']
Another way to do with only one loop is to use sort(), credit to jeremy
var array1 = ["cat", "sum","fun", "run", "gut"];
var array2 = ["bat", "cat","dog","sun", "hut", "gut"];
var arrayMatch = function(array1, array2) {
var matches = [];
array1.sort();
array2.sort();
for (var i = 0; i < array1.length; i += 1) {
if (array2.indexOf(array1[i]) > -1) {
matches.push(array1[i]);
}
}
return matches;
}
console.log(arrayMatch(array1,array2))
And yet another way to do it is by using Array.prototype.filter, credit to Paul S.
var array1 = ['DETE', 'Ivany', 'James', 'Don', 'Crakcer']
var array2 = ['Jamies', 'Ivanyy', 'DETE', 'Don']
function arrayMatch(array1, array2) {
var t;
if (array1.length > array2.length) t = array2, array2 = array1, array1 = t;
return array1.filter(function (e) {
return array2.indexOf(e) > -1;
});
}
console.log(arrayMatch(array1, array2));

Create arrays from JavaScript objects

I have some data which looks like this:
{
"obj":
[
{
"name": "name1",
"age": "24"
},
{
"name": "name2",
"age": "17"
}
]
}
What I need to do is to create 2 arrays from it.
For example:
namelist[];
agelist[];
so the result would be:
namelist: ['name1', 'name2'];
agelist: [24, 17];
My question is, how can I do this?
var namelist = [];
var agelist = [];
for(var i in obj.obj){
namelist.push(obj.obj[i].name);
agelist.push(obj.obj[i].age);
}
console.log(namelist, agelist);
Is this what U wanted ?
var zz={
"obj": [
{
"name": "name1",
"age": "24"
},
{
"name": "name2",
"age": "17"
}
]
}
namelist=[];
agelist=[];
zz.obj.forEach(function(rec){
namelist.push(rec.name);
agelist.push(rec.age);
})
console.log(namelist,agelist)
You could use this ES6 code, and use the unitary plus for getting the ages as numbers. Assuming your object is stored in variable data:
var namelist = data.obj.map( o => o.name );
var agelist = data.obj.map( o => +o.age );
var data = {
"obj": [
{
"name": "name1",
"age": "24"
},
{
"name": "name2",
"age": "17"
}
]
};
var namelist = data.obj.map( o => o.name );
var agelist = data.obj.map( o => +o.age );
console.log(namelist);
console.log(agelist);
var arr = $.map(myObj, function(value, index) {
return [value];
});
console.log(arr);
if you are not using Jquery then:
var arr = Object.keys(myObj).map(function (key)
{ return obj[key];
});`
Make use of jquery map function or otherwise you can loop over the object and push it into array using javascript for loop and use the push() function. Refer Loop through an array in JavaScript
Jquery
var data = {
"obj": [
{
"name": "name1",
"age": "24"
},
{
"name": "name2",
"age": "17"
}
]
}
var name = $.map(data.obj, function(value, index) {
return value.name;
});
var age = $.map(data.obj, function(value, index) {
return value.age;
});
console.log(name);
console.log(age);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Javascript
var data = {
"obj": [
{
"name": "name1",
"age": "24"
},
{
"name": "name2",
"age": "17"
}
]
}
var names = [], ages=[];
data.obj.forEach(function(value, index) {
names.push(value.name);
ages.push(value.age);
});
console.log(names,ages);

Loop through object and its array

Say i have an array with several objects, looking like this:
{
"firstname": John,
"lastname": "Doe",
"numbers": [{
"id": 1,
"value": "123"
}, {
"id": 2,
"value": "123"
}],
}, ...
How do i loop through these objects while also looping through their "numbers" property?
var input = {
"firstname": "John",
"lastname": "Doe",
"numbers": [{
"id": 1,
"value": "123"
}, {
"id": 2,
"value": "123"
}]
}
for (var key in input) {
if (key === "numbers") {
for (var i=0; i < input[key].length; i++) {
console.log(input[key][i]);
}
} else {
console.log(key + ":" + input[key])
}
}
Nested loop:
var input = [{
"firstname": John,
"lastname": "Doe",
"numbers": [{
"id": 1,
"value": "123"
}, {
"id": 2,
"value": "123"
}],
}]
input.forEach(function(item) {
item.numbers.forEach(function(number) {
console.log(number.id, number.value)
}
}
This one uses recursion so it will work even if the pattern isn't the same:
function looopAllTheThings(theThings, theCallback, depth){
if(undefined===depth) depth = 0;
if(typeof theThings == "object"){
for(var p in theThings)
if(theThings.hasOwnProperty(p))
if("object" == typeof theThings[p] ||
"array" == typeof theThings[p])
looopAllTheThings(theThings[p], theCallback, (depth+1));
else theCallback(p, theThings[p], depth);
}else if(typeof theThings == "array"){
for(var i=0; i<theThings.length; i++)
if("object" == typeof theThings[i] ||
"array" == typeof theThings[i])
looopAllTheThings(theThings[i], theCallback, (depth+1));
else theCallback(p, theThings[i], depth);
}else{
theCallback(null, theThings, depth);
}
}
Use it like this:
looopAllTheThings(data, function(key, value, depth){
document.getElementById('out').innerHTML += ("-".repeat(depth))+" "+key+" = "+value+"<br>";
});
Here's a fiddle: https://jsfiddle.net/2o2Lyayj/

Compare two objects in jQuery and get the difference [duplicate]

This question already has answers here:
How to get the difference between two arrays in JavaScript?
(84 answers)
Closed 7 years ago.
Using jQuery I would like to compare 2 objects:
sourceArray:
var origArray = [{
"Name": "Single",
"URL": "xxx",
"ID": 123
},
{
"Name": "Double",
"URL": "yyy",
"ID": 345
},
{
"Name": "Family",
"URL": "zzz",
"ID": 567
}];
destination array
var destArray = [{
"Name": "Single",
"URL": "xxx",
"ID": 123
},
{
"Name": "Double",
"URL": "yyy",
"ID": 888
},
{
"Name": "Family",
"URL": "zzz",
"ID": 567
}];
What I would like to do, is compare the target object with the source object based on the ID and find the mis-matched entries with a description on the resultant object. So the result will look like this:
var resultArray = [{
"Name": "Double",
"URL": "yyy",
"ID": 888,
"desc": "missing in source"
},
{
"Name": "Double",
"URL": "yyy",
"ID": 345,
"desc": "missing in destination"
}];
Any quick help is really appreciated.
This isn't a good use of jQuery, but here is some vanilla javascript that does what you want.
function objDiff(array1, array2) {
var resultArray = []
array2.forEach(function(destObj) {
var check = array1.some(function(origObj) {
if(origObj.ID == destObj.ID) return true
})
if(!check) {
destObj.desc = 'missing in source'
resultArray.push(destObj)
}
})
array1.forEach(function(origObj) {
var check = array2.some(function(destObj) {
if(origObj.ID == destObj.ID) return true
})
if(!check) {
origObj.desc = 'missing in destination'
resultArray.push(origObj)
}
})
return resultArray
}
https://jsfiddle.net/9gaxsLbz/1/
If you are wanting to dedupe your array, this will work:
var merged = origArray.concat(destArray);
var unique = merged.filter(function(item) {
return ~this.indexOf(item.ID) ? false : this.push(item.ID);
}, []);
Fiddle: https://jsfiddle.net/Ljzor9c6/
If you are only wanting items that were duped, you can easily invert the condition:
var merged = origArray.concat(destArray);
var dupes = merged.filter(function(item) {
return ~this.indexOf(item.ID) ? true : !this.push(item.ID);
}, []);
You can loop through the items in the first array and put the ID's in a map, then loop through the items in the second array and remove the matching ID's and add the missing.
Then just loop through the map to create the objects in the resulting array:
var origArray = [{
"Name": "Single",
"URL": "xxx",
"ID": 123
},
{
"Name": "Double",
"URL": "yyy",
"ID": 345
},
{
"Name": "Family",
"URL": "zzz",
"ID": 567
}];
var destArray = [{
"Name": "Single",
"URL": "xxx",
"ID": 123
},
{
"Name": "Double",
"URL": "yyy",
"ID": 888
},
{
"Name": "Family",
"URL": "zzz",
"ID": 567
}];
var map = {};
for (var i = 0; i < origArray.length; i++) {
map[origArray[i].ID] = 'source';
}
for (var i = 0; i < destArray.length; i++) {
var id = destArray[i].ID;
if (id in map) {
delete map[id];
} else {
map[id] = 'destination';
}
}
var resultArray = [];
for (key in map) {
var arr = map[key] == 'source' ? origArray : destArray;
for (var i = 0; arr[i].ID != key; i++) ;
resultArray.push({
Name: arr[i].Name,
URL: arr[i].URL,
ID: arr[i].ID,
desc: 'missing in ' + map[key]
});
}
// show result in StackOverflow snippet
document.write(JSON.stringify(resultArray));
var result = [];
for(var i = 0; i < oa.length; i++) {
var idx = mIndexOf(oa[i].ID);
if(idx > -1) {
oa.splice(i, 1);
da.splice(idx, 1);
}
}
for(var i = 0; i < oa.length; i++) {
var ln = result.length;
result[ln] = oa[i];
result[ln].desc = "missing in destination";
}
for(var i = 0; i < da.length; i++) {
var ln = result.length;
result[ln] = da[i];
result[ln].desc = "missing in origin";
}
function mIndexOf(id) {
for(var i = 0; i < oa.length; i++)
if(oa[i].ID == id)
return i;
return -1;
}
console.log(result);
0: Object
ID: 345
Name: "Double"
URL: "yyy"
desc: "missing in destination"
1: Object
ID: 888
Name: "Double"
URL: "yyy"
desc: "missing in origin"
jsfiddle DEMO
For things like this, you should use lodash. With lodash you can just do this:
var resultArray = _.defaults(destArray, origArray);

javascript filter of array with titles

I have the following code (using Chrome)
<script>
var arr = [{
"id": 1,
"fn": "bill",
"ln": "blogs"
}, {
"id": 2,
"fn": "jim",
"ln": "jones"
}, {
"id": 3,
"fn": "bill",
"ln": "smith"
}];
var lookFor = "bill";
var result = arr.filter(function(item) {
return if (item.ln == lookFor) return true;
});
alert(result.length);
alert(result[0]["id"] + result[0]["fn"] + result[0]["ln"]);
</script>
I am trying to filter the array and return those that the first name (fn) is bill. Returning id, fn, and ln in a messagebox.
I am probably missing some knowledge of the syntax of this.
Try this
var result = arr.filter(function(item) {
return item.fn === lookFor;
});
....return those that the first name (fn) is bill
But in your code you use item.ln. Also why do you use two return statement
return if (item.ln == lookFor) return true;
You need just return true or false and you can do it like this
return item.fn === lookFor;
if item.fn equals lookFor it will be true, otherwise false
Example
You should be using
var arr = [{
"id": 1,
"fn": "bill",
"ln": "blogs"
}, {
"id": 2,
"fn": "jim",
"ln": "jones"
}, {
"id": 3,
"fn": "bill",
"ln": "smith"
}];
var lookFor = "bill";
var result = arr.filter(function(item) {
return item.ln === lookFor;
});
alert(result.length);
alert(result[0]["id"] + result[0]["fn"] + result[0]["ln"]);
But I guess its not ln which you want, instead you want fn cause their is no ln which is equal to bill.

Categories

Resources