I was trying to populate a table with knockout integration. That takes data from Json.
JSON DATA
{
"info":[
{
"Name":"Noob Here",
"Major":"Language",
"Sex":"Male",
"English":"15",
"Japanese":"5",
"Calculus":"0",
"Geometry":"20"
},
{
"Name":"Noob Here",
"Major":"Calculus",
"Sex":"Female",
"English":"0.5",
"Japanese":"40",
"Calculus":"20",
"Geometry":"05"
}
]
}
I used knockout-mapping to dynamically map the data into the page. That has been added as Javascript in JS-bin. My script is in the sample's html page
$(document).ready(function () {
$("#div1").append("<tr><td data-bind='text: name'></td><td data-bind='text: major'></td><td data-bind='text: sex'></td><td><input data-bind='value: English' /></td><td><input data-bind='value: Japanese' /></td><td><input data-bind='value: Calculus' /></td><td><input data-bind='value: Geometry' /></td></tr>");
function loadData(fileName) {
var data = {
"info": [{
"Name": "Noob Here",
"Major": "Language",
"Sex": "Male",
"English": "15",
"Japanese": "5",
"Calculus": "0",
"Geometry": "20"
}, {
"Name": "Noob Here",
"Major": "Calculus",
"Sex": "Female",
"English": "0.5",
"Japanese": "40",
"Calculus": "20",
"Geometry": "05"
}]
}
return (data);
}
var dataFunction = function () {
this.Items = ko.observableArray([]);
};
var myFile = "Data";
var data = [];
var data1 = {
"info": [{
"Name": "Noob Here",
"Major": "Language",
"Sex": "Male",
"English": "15",
"Japanese": "5",
"Calculus": "0",
"Geometry": "20"
}, {
"Name": "Noob Here",
"Major": "Calculus",
"Sex": "Female",
"English": "0.5",
"Japanese": "40",
"Calculus": "20",
"Geometry": "05"
}]
}
if (data1 && data1.info) {
console.log(data1.info[0]);
$.each(data1.info[0], function (key, value) {
});
$.each(data1.info, function (index, element) {
data.push({
English: element.English,
Japanese: element.Japanese,
Calculus: element.Calculus,
Geometry: element.Geometry,
name: element.Name,
major: element.Major,
sex: element.Sex
});
});
dataFunction.prototype = function () {
var getAllItems = function () {
var self = this;
ko.mapping.fromJS(data, {}, self.Items);
};
var finalObj = {};
var info = [];
$.each(data1.info, function (i, v) {
var object = {};
$.each(v, function (i1, val1) {
if ($.isNumeric(val1)) {
object[i1] = val1
}
});
info.push(object);
});
finalObj['info'] = info;
console.log(finalObj);
return {
getAllItems: getAllItems
}
}();
var dataList = new dataFunction();
dataList.getAllItems();
ko.applyBindings(dataList);
}
});
I want to replace
data.push({
English: element.English,
Japanese: element.Japanese,
Calculus: element.Calculus,
Geometry: element.Geometry,
name: element.Name,
major: element.Major,
sex: element.Sex
});
Into a dynamic script so that what ever json data i add will be shown in the table format. Even if its column name or column number changes.
Does anyone know how to do it?
http://jsbin.com/ipeseq/1/
Assuming that the change in case for name, major and sex is not an actual requirement, you can just push the object.
data.push(element);
As is you're basically creating a copy of the element piece by piece and pushing that, why not just push the element itself?
Related
I planed to prepare this array by separate those kind of array with index specification
Default data format
[{
"Emp_code": "EM-00001",
"Emp_title": "11",
"Emp_firstName": "22",
"Emp_lastName": "33",
"Emp_dateOfBirth": "20-10-1985",
"Con_title": "title",
"Con_email": "email",
"Con_addres": "address",
"Con_phone": "phone"
}]
Wanted format
[{
"emp": {
"code": "EM-00001",
"title": "11",
"firstName": "22",
"lastName": "33",
"dateOfBirth": "20-10-1985",
},
"con": {
"Con_title": "title",
"Con_email": "email",
"Con_addres": "address",
"Con_phone": "phone"
}
}]
You can reduce the property names to a starting accumulator of [{ emp: {} }, { con: {} }] and each iteration you can add the property to the corresponding item in the accumulator.
const data = [{
"Emp_code": "EM-00001",
"Emp_title": "11",
"Emp_firstName": "22",
"Emp_lastName": "33",
"Emp_dateOfBirth": "20-10-1985",
"Con_title": "title",
"Con_email": "email",
"Con_addres": "address",
"Con_phone": "phone"
}];
const format = obj =>
Object.getOwnPropertyNames(obj[0]).reduce(
(acc, prop) => {
if (prop.startsWith('Emp_')) {
acc[0].emp[prop.replace('Emp_', '')] = obj[0][prop];
} else {
acc[1].con[prop] = obj[0][prop];
}
return acc;
},
[{ emp: {} }, { con: {} }]
);
console.log(format(data));
var item = {
"Emp_code": "EM-00001",
"Emp_title": "11",
"Emp_firstName": "22",
"Emp_lastName": "33",
"Emp_dateOfBirth": "20-10-1985",
"Con_title": "title",
"Con_email": "email",
"Con_addres": "address",
"Con_phone": "phone"
}
var data = [item, item];
var res = []
for (var item of data) {
var temp = {};
res.push(temp);
for (var prop in item) {
var parts = prop.split('_');
var prefix = parts[0].toLowerCase();
temp[prefix] = temp[prefix] || {};
temp[prefix][prefix === 'emp' ? parts[1] : prop] = item[prop]
}
}
console.log(res);
Below script checks element using loops, then splits them into prefix & suffix. Then checks for whether prefix is present in resulting array or not. If it's not then adds that prefix into array & prepares the result.
var a = [{"Emp_code": "EM-00001", "Emp_title": "11", "Emp_firstName": "22", "Emp_lastName": "33", "Emp_dateOfBirth": "20-10-1985", "Con_title": "title", "Con_email": "email", "Con_addres": "address", "Con_phone": "phone"}];
var b = [];
$.each(a, function(arrKey, arrData){
var tempArr = {};
$.each(arrData, function(key, value){
var arrKey = key.split('_');
var prefix = arrKey[0];
var suffix = arrKey[1];
if( $.inArray(prefix, Object.keys(tempArr)) == -1 ) {
tempArr[prefix] = {};
}
tempArr[prefix][suffix]=value;
});
b.push(tempArr);
});
console.log(b);
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>
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 json object It can be nested and I have an second object containing key/value pair. I want to replace the second object's value by first one by matching key both object's key.
let firstObj = {
"enquiry": {
"Lead": {
"SubLead": {
"DealerRef": "test",
"DealerFloor": "test",
"Region": "test",
"Source": {
"Special": "test",
"TestDrive": "test",
"TradeIn": "test",
"Finance": "test"
}
},
"Contact": {
"Info": {
"FirstName": "test",
"Surname": "test",
"Email": "test",
"OfficePhone": "test",
"CellPhone": "test"
}
},
"Seeks": {
"Stock": {
"Used": "test",
"Brand": "test",
"Model": "test",
"StockNr": "test"
}
}
}
}
}
Its my array
let secondObj = {
DealerRef: '18M',
DealerFloor: 'UCP',
Region: 'Western Cape',
FirstName: 'abc',
Surname: 'xyz',
Email: 'test#ctm.co.za',
OfficePhone: '2343243',
CellPhone: '2343243',
Used: '1',
Brand: 'QAE',
Model: 'test',
StockNr: 'SEDONA',
Special: '2013 Kia Sedona',
TestDrive: '0',
TradeIn: '0',
Finance: '0'
};
I have tried many ways [http://jsfiddle.net/FM3qu/7/][1] this way i'm able to get solution in Jsfiddle, In my express application when I try to process it gives me an empty object.
I want something like this
"enquiry": {
"Lead": {
"SubLead": {
"DealerRef": "18M",
"DealerFloor": "UCP",
"Region": "Western Cape"....
Thank you
You could first save all references and then assign the data, you have.
function update(object, data) {
function getAllKeys(o) {
Object.keys(o).forEach(function (k) {
if (typeof o[k] === 'object') {
return getAllKeys(o[k]);
}
keys[k] = o;
});
}
var keys = Object.create(null);
getAllKeys(object);
Object.keys(data).forEach(function (k) {
if (keys[k] && k in keys[k]) { // check if key for update exist
keys[k][k] = data[k];
}
});
}
var object = { "enquiry": { "Lead": { "SubLead": { "DealerRef": "test", "DealerFloor": "test", "Region": "test", "Source": { "Special": "test", "TestDrive": "test", "TradeIn": "test", "Finance": "test" } }, "Contact": { "Info": { "FirstName": "test", "Surname": "test", "Email": "test", "OfficePhone": "test", "CellPhone": "test" } }, "Seeks": { "Stock": { "Used": "test", "Brand": "test", "Model": "test", "StockNr": "test" } } } } },
data = { DrNo: 666, DealerRef: '18M', DealerFloor: 'UCP', Region: 'Western Cape', FirstName: 'abc', Surname: 'xyz', Email: 'test#ctm.co.za', OfficePhone: '2343243', CellPhone: '2343243', Used: '1', Brand: 'QAE', Model: 'test', StockNr: 'SEDONA', Special: '2013 Kia Sedona', TestDrive: '0', TradeIn: '0', Finance: '0' };
update(object, data);
console.log(object);
You can iterate through firstObj and replace key/value with secondObj
function iterateObj(obj){
for(var key in obj){
if(obj.hasOwnProperty(key)){
if(typeof obj[key] === 'object'){
iterateObj(obj[key]);
}
else if(secondObj[key]!=undefined){
obj[key] = secondObj[key]
}
}
}
}
iterateObj(firstObj)
console.log(firstObj); // this will give proper results
I need to access the second array from a JSON decoded string, but I am having no luck.
The entire JSON string is displayed in var RAW00, and then split into var RAW01 & var RAW02.
All 3 of these are for testing - RAW00 is identical to msg
When they are split - I can access either, depending on what variable I start of with, but when I use RAW00 I cannot access the tutor section.
I will provide more detail if required, but my question is:
How do I see and access the tutor array in the second $.each (nested) block??]
Thanks :-)
success: function(msg)
{
var test = "";
var raw00 = {
"allData": [
{
"class2": [
{
"tid": "1",
"name": "Monday 2"
},
{
"tid": "1",
"name": "Monday Test"
}
]
},
{
"tutor": [
{
"fname": "Jeffrey",
"lname": "Kranenburg"
},
{
"fname": "Jeffrey",
"lname": "Kranenburg"
}
]
}
]
};
var raw01 = {
"allData": [
{
"class2": [
{
"tid": "1",
"name": "Monday 2"
},
{
"tid": "1",
"name": "Monday Test"
}
]
}
]
};
var raw02 = {
"allData": [
{
"tutor": [
{
"fname": "Jeffrey",
"lname": "Kranenburg"
},
{
"fname": "Jeffrey",
"lname": "Kranenburg"
}
]
}
]
};
$.each(raw00.allData, function(index, entry)
{
$.each(entry.class2, function (index, data)
{
console.log(this.name);
test += '<tr><td>'+this.name+'</td>';
});
$.each(entry.tutor, function (index, data)
{
console.log(this.fname);
test += '<td>'+this.name+'</td></tr>';
});
$('#all-courses-table-content').html( test );
});
You need to check whether the current element of the array is an object with class2 property or tutor property.
$.each(raw00.allData, function(index, entry) {
if (entry.hasOwnProperty('class2')) {
$.each(entry.class2, function (index, data)
{
console.log(this.name);
test += '<tr><td>'+this.name+'</td>';
});
}
if (entry.hasOwnProperty('tutor')) {
$.each(entry.tutor, function (index, data)
{
console.log(this.fname);
test += '<td>'+this.fname+'</td></tr>';
});
}
$('#all-courses-table-content').html( test );
});
Things would probably be simpler if you redesigned the data structure. It generally doesn't make sense to have an array of objects when each object just has a single key and it's different for each. I suggest you replace the allData array with a single object, like this:
var raw00 = {
"allData": {
"class2": [
{
"tid": "1",
"name": "Monday 2"
},
{
"tid": "1",
"name": "Monday Test"
}
],
"tutor": [
{
"fname": "Jeffrey",
"lname": "Kranenburg"
},
{
"fname": "Jeffrey",
"lname": "Kranenburg"
}
]
}
};