Reading JSON object value with key pattern - javascript

My JSON structure is as follows
var data = [
{name:'bracket', start_45641654:'46513489431',end_26441:'75434'},
{ name: 'notation', end_746413: '2146464', start_51345641: '76542464' },
];
I want to print start, end object values, Here a random number is appending to keys start_ and end_. Tried to use ^ regular expression pattern but it is not working. Is there any other way to print the values?
data.forEach(function (v, i) {
$('tr').prepend('<td>Name:' + v['name'] + '</td>' +
'<td>Start:' + v['^start_'] + '</td>' +
'<td>End:' + v['^end_'] + '</td>'
);
});

You can't use regular expressions there.
You can loop through the properties of the object, checking if the name has the desired prefix.
data.forEach(function(v) {
let start, end;
Object.entries(v).forEach(([key, val]) => {
if (key.startsWith('start_')) {
start = val;
} else if (key.startsWith('end_')) {
end = val;
}
});
$('tr').prepend('<td>Name:' + v.name + '</td>' +
'<td>Start:' + start + '</td>' +
'<td>End:' + end + '</td>'
);
});

var data = [
{name:'bracket', start_45641654:'46513489431',end_26441:'75434'},
{ name: 'notation', end_746413: '2146464', start_51345641: '76542464' },
];
data.forEach(function (v, i) {
var start = Object.keys(v).find((name) => /start/.test(name));
var end = Object.keys(v).find((name) => /end/.test(name));
console.log(start+" "+end);
$('tr').prepend('<td>Name:' + v['name'] + '</td>' +
'<td>Start:' + v[start] + '</td>' +
'<td>End:' + v[end] + '</td>'
);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr></tr>
</table>
Check this. I don't know if accessing object keys using regex and indexing works. But this should work for you.

Note: I write it on the fly you may need to tweak it
for(let item of data) { // iterate through array
for(let key in item) { // iterate through object keys
if(!key.hasOwnProperty()) // you may wont need it, it makes sure the key you are bringing aren't inherited and the current object is owner of them, mostly used with arrays
return
if(key.indexof('start_') >= 0) // which should be 0 if is ok and -1 if not ok
{
// your code for start
// to get value: item[key]
}
if(key.indexof('end_') >= 0) // which should be 0 if is ok and -1 if not ok
{
// your code for end
// to get value: item[key]
}
}
}
Note: that you may read your JSON file/resource as string, not an object (depend on method used), in that case use JSON.parse(<yourStringJson>)

You can achieve this using reduce function of array. You don't need to use for, for each loop and condition related logic.
For example:
const data = [
{ name: "bracket", start_45641654: "46513489431", end_26441: "75434" },
{ name: "notation", end_746413: "2146464", start_51345641: "76542464" },
];
console.log(data);
const startEndData = data.reduce((p, c) => {
const { name, ...rest } = c;
return [...p, rest];
}, []);
console.log(startEndData);

Related

How to change counter variable from numbers to letters?

How can I change a counter variable from a number to a letter? Say I have five sections that each read "Section A", "Section B", so on... And I want to change their href attributes as they are being mapped out from "section1" to "sectionA", "section2" to "sectionB", etc?
var sectionNumberLink = 0;
var sectionLetters = assessmentSections.map(function (section) {
sectionNumberLink++;
return '<div class="assess-sec-link">' + '<a href="section' +
sectionNumberLink + '">' + "Section" + '</a>' + '</div>';
}).join('');
You can use String.fromCharCode() and String.prototype.charCodeAt() to convert the number to a letter
Example:
Warning: This will fail if you have more than 26 sections
function toLetter(number) {
let base = 'A'.charCodeAt(0);
return String.fromCharCode(base - 1 + number);
}
console.log(toLetter(1)); // A
console.log(toLetter(2)); // B
If you need more than 26 sections, a bit more code is required:
function toLetter(num) {
let a = "A".charCodeAt(0);
let result = '';
for (let base = 1, mod = 26; (num -= base) >= 0;base = mod, mod *= 26) {
result = String.fromCharCode(num % mod / base + a) + result;
}
return result;
}
console.log(toLetter(1)); // A
console.log(toLetter(27)); // AA
In your code snippet you could use it like this:
let sectionLetters = assessmentSections.map((section, idx) => {
return `
<div class="assess-sec-link">
Section
</div>`;
}).join('');
You can use index to calculate the alphabet in the .map() method,
//sample
var assessmentSections = ["section1", "section2", "section3"]
var sectionLetters = assessmentSections.map(function (section, index) {
return '<div class="assess-sec-link">' + '<a href="section' +
String.fromCharCode('A'.charCodeAt(0) - 1 + (index+1)) + '">' + "Section" + '</a>' + '</div>';
}).join('');
console.log(sectionLetters)
You could do something like:
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
//As #georg suggested, you could do it like:
for(let c=1;c<=alphabet.length;c++){
console.log("Section "+alphabet[c-1])
}
So, you can call alphabet[number-1] to change NUMBER to CHARACTER.
Remember arrays indexes start from 0, that's why it needs to be number-1.
I would try to structure my HTML so I can use an <ol type="A"> instead of <div>s, so that I get automatic ordering with uppercase letters automatically, without me having to do index-to-letter calculations:
// create dummy data
var assessmentSections = Array.from({ length: 50 }, ( item, i ) => {
return { url: i + 1 };
});
var sections = assessmentSections.map(( section, i ) => {
return `<li class="assess-sec-link">Section ${ i + 1 }</li>`;
});
document.querySelector( 'ol' ).innerHTML = sections.join( '' );
<ol type="A"></ol>

How to access all nested associative array elements?

Situation : I receive JSON array from jQuery <-> PHP Ajax request. Here's structure of unparsed JSON aray :
{"Focus":{"id":2,"brand":"Ford","name":"Focus"}}
And after using JSON.parse(json); the structure looks like :
Focus: Object
brand: "Ford"
id: 2
name: "Focus"
Problem : I want to access all array's '1st tier' elements and use them like an object, but none of the following ways works :
for (var entity in dataTable)
{
formattedText += entity['brand'] + " " + entity['name'] + "<br>";
OR
formattedText += entity.brand + " " + entity.name + "<br>";
OR
formattedText += dataTable[0]['brand'] + " " + dataTable[0]['name'] + "<br>";
}
Any solutions how to read values of all object in this array?
The for..in loop uses keys and does not return the elements themself: for (var key in dataTable)You would then access each element with dataTable[key]. The key is actually the name of the Element.
You where using it as you would use a for..of loop, but that is a new feature not supported in all Browsers yet.
Demo:
var dataTable = {"Focus":{"id":2,"brand":"Ford","name":"Focus"}}
var formattedText = ""
for (var key in dataTable)
{
formattedText += dataTable[key]['brand'] + " " + dataTable[key]['name'] + "<br>";
}
document.write(formattedText)
Object.keys will return array of all the keys of the object
You can loop(forEach/for-loop) through the keys to get the expected output.
Using forEach:
var dataTable = {
"Focus": {
"id": 2,
"brand": "Ford",
"name": "Focus"
}
}
var keys = Object.keys(dataTable);
var str = '';
keys.forEach(function(item) {
str += dataTable[item].brand + " " + dataTable[item].name;
});
alert(str);
Using for-loop:
var dataTable = {
"Focus": {
"id": 2,
"brand": "Ford",
"name": "Focus"
}
}
var keys = Object.keys(dataTable);
var str = '';
for (var i = 0, len = keys.length; i < len; i++) {
str += dataTable[keys[i]].brand + " " + dataTable[keys[i]].name;
}
alert(str);
The correct syntax to write this would be:
When you loop, you'll get the key name in the variable entity and then use that to get the value, also, you need to access the associative array inside the first key i.e. Focus
var dataTable = JSON.parse('{"Focus":{"id":2,"brand":"Ford","name":"Focus"}}');
var formattedText = '';
for (var entity in dataTable.Focus) {
formattedText += dataTable.Focus['brand'] + " " + dataTable.Focus['name'] + "<br>";
}
Sounds like you're using each function in a wrong way. in your each function change arguments to key and value like this:
$.each(dataTable, function (key, value) {
//access key and values here
});
In your case u should iterate again over key and values of your key values.

How to rerender data in a javascript table orderd by a specific column

By javascript I generate rows for Agents in a table. every row represent an agent. after this I receive live data to update the columns. I have a column called (Calls) and i need to order the agents by calls (live update depending on received data) descending. example
agents ----- calls
Sam ---------13
Al ---------12
Sara---------8
if Sara got the most data by time then she'll be the first.
agents -------calls
Sara----------15
Sam ----------13
Al------------12
and so on ..
this is my row rendering
var $agentRow = '<tr id="agentRow_' + agentId + '"><th scope="row">' + agentName + '</th><td class="calls" id="agentCalls_' + agentId + '">' + outTotalCalls +
'</td><td class="minutes" id="agentMinutes_' + agentId + '">' +
outCallMinutes + '</td>' +
'<td class="averages" id="agentAverage_' + agentId + '">' + averageOutCallTime + '</td></tr>';
//if $agentRow exists invoke setIncomingValuesToAgentsFields else append it to the table
if ($('#agentRow_' + agentId).length) {
setIncomingValuesToAgentsFields('#agentCalls_' + agentId, outTotalCalls);
setIncomingValuesToAgentsFields('#agentMinutes_' + agentId, outCallMinutes);
setIncomingValuesToAgentsFields('#agentAverage_' + agentId, averageOutCallTime);
} else {
$('#agentsTable').append($agentRow);
}
function setIncomingValuesToAgentsFields(elementId, inComingValue) {
var currentElementValue = 0;
if ($(elementId).text() !== "") {
currentElementValue = $(elementId).text();
currentElementValue = parseFloat(currentElementValue);
currentElementValue += inComingValue;
$(elementId).text(currentElementValue);
} else {
$(elementId).text(currentElementValue);
}
}
See the live sample of what you need. After 3 second Al calls become 14, and table rows will be sorted again.
var agents = [
{ name: 'Sara', calls : 15 },
{ name: 'Sam', calls : 13 },
{ name: 'Al', calls : 12 }
];
function to_row(obj){
var tr = $('<tr></tr>');
tr.data('obj', obj);
$('<td>'+obj.name+'</td>').appendTo(tr);
$('<td>'+obj.calls+'</td>').appendTo(tr);
return tr;
}
function table_update(obj){
$('#table tr').each(function(){
var t=$(this);
var o=t.data('obj');
if(o.name==obj.name){
t.remove();
};
if(o.calls>obj.calls){
to_row(obj).insertAfter(t);
}
return t.data('obj');
})
}
agents.sort(function(x,y){
return y.calls - x.calls;
}).forEach(function(o){
to_row(o).appendTo( $('#table') );
});
setTimeout(function(){
table_update( { name: 'Al', calls : 14 } );
}, 3000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table">
</table>
Hope you will be getting data from server using Ajax call . So If your having the result data in JSON object , then you can sort the data to find out which is having highest value . The follwing functon will help us to sort the data
sortTable:function (property,asc)
{
sampleTableObject = sampleTableObject.sort(function(a, b) {
if (asc) return (a[property] > b[property]) ? 1 : ((a[property] < b[property]) ? -1 : 0);
else return (b[property] > a[property]) ? 1 : ((b[property] < a[property]) ? -1 : 0);
});
}
property is the json object property (here it should be calls) based on which you need to sort .
Pass false to 'asc' to sort in descending order.
Assign sampleTableObject with the result json object and call sortTable() . Then use the sorted object to build the table.

How can iterate over JSON object and print its properties and their values?

I want to navigate each property in the JSON below in JavaScript. The below JSON contains two records for reference but in real time will have numerous such records.
{"Record_0":[{"Status":"CREATED","CreatorLoginId":"sandhya","Name":"G1"}],"Record_1":[{"Status":"CREATED","CreatorLoginId":"San","Name":"G2"}]}
I want to get the values of the fields "Status", "CreatorLoginId" and "Name" to assign them to something else.
How should I do it?
var myJSON = JSON.parse('{"Record_0":[{"Status":"CREATED","CreatorLoginId":"sandhya","Name":"G1"}],"Record_1":[{"Status":"CREATED","CreatorLoginId":"San","Name":"G2"}]}');
for(var pr in myJSON)
{
console.log(myJSON[pr][0].Status);
console.log(myJSON[pr][0].CreatorLoginId);
console.log(myJSON[pr][0].Name);
}
Print how? If you mean output to the js console it would be
for (index in object) {
console.log(index + ': ' + object[index]);
}
If you mean add it to a web page, just replace console.log with a little markup:
var parent = document.getElementById('parentID');
for (index in object) {
parent.innerHTML += index + ': ' + object[index] + '<br>';
}
For nested objects (including arrays)
function print(object, parent) {
for (index in object) {
if (typeof object[index] == 'object') {
print(object[index});
}
parent.innerHTML += index + ': ' + object[index] + '<br>';
}
}
EDIT: don't forget to JSON.parse(): the string first before iterating
//Iterating through the groups
for (var currentRecord in groupInformation)
{
store.data.items.push({serial: {}, groupName: {}, createdBy: {}, status: {} });
store.data.items[iNoOfGroups].serial = iNoOfGroups + 1;
store.data.items[iNoOfGroups].groupName = groupInformation[currentRecord][0].Name;
store.data.items[iNoOfGroups].createdBy = groupInformation[currentRecord][0].CreatorLoginId;
store.data.items[iNoOfGroups].status = groupInformation[currentRecord][0].Status;
iNoOfGroups++;
}
var myJSON = JSON.parse('{"Record_0":[{"Status":"CREATED","CreatorLoginId":"sandhya","Name":"G1"}],"Record_1":[{"Status":"CREATED","CreatorLoginId":"San","Name":"G2"}]}');
for(var key in myJSON){
console.log(myJSON[key][0].Status);
console.log(myJSON[key][0].CreatorLoginId);
console.log(myJSON[key][0].Name);
}`

Loop through jquery data() object to get keys and values

I have a data() object containing some json.
Is there a way I can loop through the object and grab each parts key and value?
This is what I have so far:
function getFigures() {
var propertyValue = getUrlVars()["propertyValue"];
$.getJSON(serviceURL + 'calculator.php?value=' + propertyValue, function(data) {
figures = data.figures;
$.each(figures, function(index, figure) {
$('#figureList').append('<li> index = ' + data.figures.figure + '</li>');
});
});
$('#figureList').listview('refresh');
}
The json looks like this:
{"figures":{"value":"150000","completion":"10.00","coal":"32.40","local":"144.00","bacs":"35.00","landRegistry":"200.00","solFee":"395.00","vatOnSolFees":79,"stampDuty":1500,"total":2395.4}}
Apologies if its simple, I'm new to jQuery and couldn't find anything on SO that helped.
You can get the key and value like this
$.each(data.figures, function(key, val) {
console.log('Key: ' + key + ' Val: ' + val)
});​
So change your code to
$('#figureList').append('<li>'+ index + ' = ' + figure + '</li>');
Demo: http://jsfiddle.net/joycse06/ERAgu/
The parameters index and figure contains the parameter name and value. I think that you want to concatenate the parameters into the string:
$('#figureList').append('<li>' + index + ' = ' + figure + '</li>');
An alternative is to create the list item element and set the text of it, that would also work if the text contains any characters that need encoding:
$('#figureList').append($('<li/>').text(index + ' = ' + figure));
function getFigures() {
var propertyValue = getUrlVars()["propertyValue"];
$.getJSON(serviceURL + 'calculator.php?value=' + propertyValue, function(data) {
$.each(data['figures'], function(index, val) {
here grab "val" is key
$.each(data['figures'][index], function(col, valc) {
here grab "col" is value
}
}
}
bye

Categories