Hi (sorry for my english), I have this script:
<script type="text/javascript">
$(document).ready(function() {
var idPlato = decodeURI(getUrlVars()["idPl"]);
var url = "http://localhost/plato-datos.php?idPla="+idPlato+"";
});
};
</script>
It brings me this json from my database:
[{"category":"first","name":"green","idP":"1", "count":3},
{"category":"first","name":"blue","idP":"2","count":5},
{"category":"sec","name":"peter","idP":"3", "count":3},
{"category":"sec","name":"james","idP":"4", "count":2,},
{"category":"third","name":"dog","idP":"5", "count":4}]
I need to create one radiobuton for every name and group by categores
I create a solution. Kinda ugly but it will work:
var data = [{
"category": "first",
"name": "green",
"idP": "1",
"count": 3
}, {
"category": "first",
"name": "blue",
"idP": "2",
"count": 5
}, {
"category": "sec",
"name": "peter",
"idP": "3",
"count": 3
}, {
"category": "sec",
"name": "james",
"idP": "4",
"count": 2,
}, {
"category": "third",
"name": "dog",
"idP": "5",
"count": 4
}];
var result = {};
data.map(a => {
if (result[a.category]) {
result[a.category].push(a.name);
} else {
result[a.category] = [a.name];
}
});
Object.keys(result).map(category => {
var select = document.createElement('select');
result[category].map(name => {
var option = document.createElement('option');
option.value = name;
option.text = name;
select.appendChild(option);
});
document.body.appendChild(select);
});
Im working with jquery mobile then i used autodividersSelector function for group by the category JSON object, and build a radiobuton for every name
<script type="text/javascript">
//catch the JSON from my database
$(document).ready(function() {
var idPla = decodeURI(getUrlVars()["idPl"]);
var urlAder =
"http://localhost/lista-adereso.php?idPla=" + idPla + "";
//print the radiobutons
$.getJSON(urlAder, function(resultado) {
var allfiles = '';
for (var i = 0, aderesos = null; i <
resultado.length; i++) {
aderesos = resultado[i];
allfiles +='<li><label><input type="radio" data-
status="' + aderesos.aderesoCatNom +'"
name="name" id="id" value="' +
aderesos.aderNombre +'">'+
aderesos.aderNombre + '</label></li>'; }
//Group by categories
$('#linkList')
.empty()
.append(allfiles)
.listview({
autodividers:true,
autodividersSelector: function ( li ) {
var out = li.find('input').data("status");
return out;
}
})
.listview("refresh");
});
});
</script>
Related
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;
I have an array of objects , each object have key and value .I want if object have same keys then their values shoud be comma sepated of all the values of same key.
my html code:
<p ng-repeat="item in allOptions" class="item" id="{{item.id}}">
{{item.id}} <input type="checkbox" ng-change="sync(bool, item)" ng-model="bool" > {{item}} Selected: {{bool}}
</p>
and my controller code is :
$scope.allOptions = [
{
"id": "1",
"data": "one",
},
{
"id": "1",
"data": "two",
},
{
"id": "2",
"data": "three",
},
];
$scope.data = [
];
$scope.sync = function(bool, item){
if(bool){
// add item
$scope.data.push(item);
} else {
// remove item
for(var i=0 ; i < $scope.data.length; i++) {
if($scope.data[i] == item.id){
$scope.data.splice(i,1);
}
}
}
};
In data array i have objects ,if we select same key of objects (same id value )then i want
{
"id": "1",
"data": "one","two",
}
var myData = [{
"id": "1",
"data": "one",
},{
"id": "1",
"data": "two",
},{
"id": "2",
"data": "three",
}];
var output = [];
//Iterating each element of the myData
myData.forEach(o => {
//Checking the duplicate value and updating the data field
let temp = output.find(x => {
if (x && x.id === o.id) {
x.data += ", " + o.data;
return true;
}
});
if(!temp)
output.push(o);
});
console.log(output);
I think, easiest way to make it would be like:
z = [
{
"id": "1",
"data": "one",
},
{
"id": "1",
"data": "two",
},
{
"id": "2",
"data": "three",
},
];
And immediate code:
var result = {};
var groupedO = {};
for(a in z){
var id = z[a].id;
var data = z[a].data;
if(groupedO[id] && groupedO[id].data){
groupedO[id].data = groupedO[id].data + ',' + data;
} else {
groupedO[id] = {data:data};
}
}
for(ind in groupedO) {
var el = groupedO[ind];
if(el.data.split(',').length > 1) { // here we take only last those, where many datas grouped in
result.id = ind;
result.data = el.data;
}
}
After this, result will look like:
{ id: "1", data: "one,two" }
If you use jQuery, then you can use $.extend() function in this code if you don't want to put reference to the object item in array hash. This means that if you change the object item in array hash, then object item in array myData change too. To avoid this, use $.extend() function.
var myData = [
{
"id": "1",
"data": "one",
},
{
"id": "1",
"data": "two",
},
{
"id": "2",
"data": "three",
},
]; // this will be your input data
function filterData(collection) {
var hash = {};
var result = [];
collection.forEach(function (item) {
if (hash[item.id]) {
hash[item.id].data += ', ' + item.data;
}
else {
hash[item.id] = $.extend({}, item);
}
});
for (var i in hash) {
result.push(hash[i]);
}
return result;
}
var filteredData = filterData(myData); //your filtered data
You can do this in following manner:
var myData = [{
"id": "1",
"data": "one",
},
{
"id": "1",
"data": "two",
},
{
"id": "2",
"data": "three",
},
]; // this will be your input data
function filterData(collection) {
var hash = {};
var result = [];
collection.forEach(function(item) {
if (hash[item.id]) {
hash[item.id].data += ', ' + item.data;
} else {
hash[item.id] = item;
}
});
for (var i in hash) {
result.push(hash[i]);
}
return result;
}
console.log(
filterData(myData) //your filtered data
)
I want to create a json using object & javascript. the function object_merge is used to merge the object values.
here is the code i'm using.
var dat0 = [{
"type": "configuration",
"Process": [{
"type": "Source",
"value": ticket_id
}],
"attributes": {
}
}];
function object_merge(){
for (var i=1; i<arguments.length; i++)
for (var a in arguments[i])
arguments[0][a] = arguments[i][a];
return arguments[0];
};
var arry = [];
var listobj= [object0,object1,object2,object3,object4,object5,object6,object7,object8,object9];
var object1 = {TicketID: [{value: ticket_id }]};
var object2 = {Score:[{value: ticket_score }]};
var object3 = {Requestor:[{value: ticket_requestor_name }]};
var object4 = {Submitter:[{value: ticket_submitter_name }]};
var object5 = {Channel:[{value: ticket_channel }]};
var object6 = {Priority:[{value: ticket_priority }]};
var object7 = {Status:[{value: ticket_status }]};
var object8 = {Subject:[{value: ticket_subject }]};
var object9 = {Group:[{value: ticket_group_name }]};
var object0 = {TicketType:[{value: ticket_type }]};
if ((object1.TicketID[0].value!== (null)||(undefined)))
{
arry.push(object1);
}
if (object2.Score[0].value!== (null)||(undefined))
{
arry.push(object2);
}
if (object3.Requestor[0].value!== (null)||(undefined))
{
arry.push(object3);
}
if (object4.Submitter[0].value!== (null)||(undefined))
{
arry.push(object4);
}
if (object5.Channel[0].value!== (null)||(undefined))
{
arry.push(object5);
}
if (object6.Priority[0].value!== (null)||(undefined))
{
arry.push(object6);
}
if (object7.Status[0].value!== (null)||(undefined))
{
arry.push(object7);
}
if (object8.Subject[0].value!== (null)||(undefined))
{
arry.push(object8);
}
if (object9.Group[0].value!== (null)||(undefined))
{
arry.push(object9);
}
if (object0.TicketType[0].value!== (null)||(undefined))
{
arry.push(object0);
}
var attr = object_merge(arry);
console.info(JSON.stringify(attr));
dat0[0].attributes = attr;
console.info(JSON.stringify(dat0));
which returns a json like
[{"type":"configuration","Process":[{"type":"Source","value":902}],"attributes":[{"TicketID":[{"value":902}]},{"Score":[{"value":"unoffered"}]},{"Requestor":[{"value":"raj"}]},{"Submitter":[{"value":"raj"}]},{"Channel":[{"value":"api"}]},{"Status":[{"value":"open"}]},{"Subject":[{"value":"sub"}]},{"Group":[{"value":"Support"}]}]}]
where as the expected result is
[{"type":"configuration","Process":[{"type":"Source","value":"902"}],"attributes":{"TicketID":[{"value":"902"}],"Score":[{"value":"unoffered"}],"Requestor":[{"value":"raj"}],"Submitter":[{"value":"raj"}],"Channel":[{"value":"api"}],"Status":[{"value":"open"}],"Subject":[{"value":"sub"}],"Group":[{"value":"Support"}]}}]
How to achieve it?
Try below code which may help you.
var attributesObject = {
"TicketID": [{
"value": "902"
}],
"Score": [{
"value": "unoffered"
}],
"Requestor": [{
"value": "raj"
}],
"Submitter": [{
"value": "raj"
}],
"Channel": [{
"value": "api"
}],
"Status": [{
"value": "open"
}],
"Subject": [{
"value": "sub"
}],
"Group": [{
"value": "Support"
}]
};
var main = [{
"type": "configuration",
"Process": [{
"type": "Source",
"value": "ticket_id"
}],
"attributes": attributesObject
}];
use this function instead of your object_merge:
function object_merge(objects) {
var newObject = {};
for (var i = 0; i < objects.length; i++)
for (var key in objects[i])
newObject[key] = objects[i][key];
return newObject;
};
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);
I have some JSON data (simple array of objects) .
var input= [
{
"cat": "some",
"id": "0"
},
{
"cat": "some",
"id": "1"
},
{
"cat": "some/category",
"id": "2"
},
{
"cat": "some/category/sub",
"id": "3"
},
{
"cat": "some/other",
"id": "4"
},
{
"cat": "some/thing/different",
"id": "5"
},
{
"cat": "some/thing/different",
"id": "6"
},
{
"cat": "yet/another",
"id": "7"
}
]
I wanted to generate nested html list out of it based on categories:
some
0
1
category
2
sub
3
other
4
thing
different
5
6
yet
another
7
My first step was to create empty nested object using the function:
createNestedObject = function(base, names) {
var = 0;
var results = [];
while (i < names.length) {
base = base[names[i]] = base[names[i]] || {};
results.push(i++);
}
return results;
}
Next i populated it with data using by spliting "cat" strings and pushing "ids" in loop (ex. some.category.sub.ids.push(7))
The final result was:
var output =
{
"some": {
"ids": [
"0",
"1"
],
"category": {
"ids": [
"2"
],
"sub": {
"ids": [
"3"
]
}
},
"other": {
"ids": [
"4"
]
},
"thing": {
"different": {
"ids": [
"5",
"6"
]
}
},
"yet": {
"another": {
"ids": [
"7"
]
}
}
}
}
However, the structure somewhat problematic because i don't know the key names and the nesting depth in advance.
How to generate nested html list out of "output" or "input" data presented here?
How about this?
Example
JS
function ToHTML(input){
var html = '<ul>';
for(var key in input){
if(input[key] instanceof Array){
for(var i = 0; i < input[key].length; i++){
html += '<li>' + input[key][i] + '</li>';
}
}else{
html += '<li>' + key + ToHTML(input[key]) + '</li>';
}
}
html += '</ul>';
return html;
}
function ToNestedObject(input){
var i, y, len = input.length, parts, partsLen, obj = {}, prev;
for(i = 0; i < len; i++){
parts = input[i].cat.split('/');
partsLen = parts.length;
prev = obj;
for(y = 0; y < partsLen; y++){
prev[parts[y]] = prev[parts[y]] || {};
prev = prev[parts[y]];
}
if(!prev.ids){
prev.ids = [];
}
prev.ids.push(input[i].id);
}
return obj;
}
var input= [
{
"cat": "some",
"id": "0"
},
{
"cat": "some",
"id": "1"
},
{
"cat": "some/category",
"id": "2"
},
{
"cat": "some/category/sub",
"id": "3"
},
{
"cat": "some/other",
"id": "4"
},
{
"cat": "some/thing/different",
"id": "5"
},
{
"cat": "some/thing/different",
"id": "6"
},
{
"cat": "yet/another",
"id": "7"
}
];
document.getElementById('test').innerHTML = ToHTML(ToNestedObject(input));
HTML
<div id='test'></div>
The array is converted into object tree
function buildTreeObject ( input ) {
var obj = {}, n ;
input.forEach( function( v ){
var keys = v.cat.split('/'),
n = obj ;
keys.forEach( function( k ){
if ( !n[k]) {
n[k] = {};
}
n = n[k];
});
n[ v.id ] = v.id ;
});
return obj;
}
and we need a function to build html
function buildHtml( obj , ul ) {
for (i in obj) {
var li = document.createElement('li');
li.innerHTML = i;
ul.appendChild( li );
if ( typeof(obj[i])== "object" ) {
childUl = document.createElement('ul');
li.appendChild( childUl );
buildHtml(obj[i], childUl );
}
}
}
and make html use of input ( ie ur array )
var ul = document.createElement('ul'),
tree = buildTreeObject( input ) ;
buildHtml( tree ,ul );
var div = document.createElement('div');
div.appendChild( ul );
console.log( div.innerHTML );
Which prints desired ul li list
You can see result in http://jsfiddle.net/r3RWL/
Since you added jquery under tags, I have written solution to your problem in jQuery. Here is the code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<div id="someDiv">
</div>
<script>
function prepareNestedStructure(input) {
var output = {},
catLevels,
currentCat;
$.each(input, function(index, catObject) {
catLevels = catObject.cat.split('/');
currentCat = output;
$.each(catLevels, function(index, name) {
if(!currentCat[name])
currentCat[name] = {};
currentCat = currentCat[name];
});
currentCat[catObject.id] = catObject.id;
});
return output;
}
function fillList(parentListEl, node) {
$.each(node, function(key, value) {
parentListEl.append('<li>' + key + '</li>');
if(jQuery.type(value) === 'object') {
var childEl = $('<ul></ul>');
parentListEl.append(childEl);
fillList(childEl, value);
}
});
}
var input= [
{
"cat": "some",
"id": "0"
},
{
"cat": "some",
"id": "1"
},
{
"cat": "some/category",
"id": "2"
},
{
"cat": "some/category/sub",
"id": "3"
},
{
"cat": "some/other",
"id": "4"
},
{
"cat": "some/thing/different",
"id": "5"
},
{
"cat": "some/thing/different",
"id": "6"
},
{
"cat": "yet/another",
"id": "7"
}
];
var output = prepareNestedStructure(input);
var ulDomElement = $('<ul></ul>');
fillList(ulDomElement, output);
$('#someDiv').append(ulDomElement);
</script>
</body>
</html>
what about this?
transform_deeply_nested_object = (dno) ->
result = ""
for key, value of dno
if value instanceof Array
result += "<ul>"
for elem in value
result += "<li>" + elem + "</li>\n"
result += "</ul>"
else
result += "<ul><li>" + key + "</li>"
result += transform_deeply_nested_object value
result += "</ul>"
Attention: Not tested!
Attention: This requires all leafs to be elements of an array always.