I keep getting [object, Object] from array for $.each when i try and alert it.
Below is the code I am using, I have tried several different ways but this seems to be the way that works the best.
Could someone please help me out
var min_chats = [];
$(function () {
$(".append_chat").click(function () {
var chatid = $(this).attr('alt');
var data = $(this).attr('data');
min_chats.push({
"chatid": chatid,
"data": data
});
});
$("#max_close").live("click", function () {
var chatid = $(this).attr('alt');
var data = $(this).attr('data');
$.each(min_chats, function (key, val) {
alert(key + val);
});
});
});
The callback parameters for $.each are index and value, not key and value.
In your case key will contain the index of the array and val will contain your object containing 2 properties: chatid and data.
So your code should look like:
$.each(min_chats, function(index, val) {
alert(val.chatid + val.data);
});
$.each documentation: http://api.jquery.com/jquery.each/
Related
Im not getting how remove chrome.storage.local values in javascript?
i use like this but the storage value is not removing from the store:chrome.storage.local.remove(result.MyFile.Base64File);
Please check the below code, here I'm using chrome.storage.local.set to set
var obj = { DocName: "name", Base64File: "Base64string" };
chrome.storage.local.set({ 'MyFile': obj });
and chrome.storage.local.get to retrive the values
chrome.storage.local.get('MyFile', function (result) {
var PdfBase64 = result.MyFile.Base64File;
var DocumentName = result.MyFile.DocName;
}
Note: You can not remove values, you can remove indexes with specific names what causes that they gets removed WITH there values.
Tbh I could not run the code but I'm pretty sure something like this should work. But I really recommend you to avoid chrome.storage because it's some kind of "dumb" :)
So please have a look at this code:
function clearItem(symbol) {
var remove = [];
chrome.storage.sync.get(function(Items) {
$.each(Items, function(index, value) {
if (index == "symbol") remove.push(index);
});
chrome.storage.sync.remove(remove, function(Items) {
chrome.storage.sync.get(function(Items) {
$.each(Items, function(index, value) {
console.log("removed: " + index);
});
});
});
});
};
I'm trying to get the first object returned by the ajax call before doing the each() loop through it. Here's the code that works for the each:
$.each(obj.DATA, function(indexInArray, value) {
var depts = value[departmentListIndex];
console.log("test",depts);
});
What I'd like to do is this:
$.each.first(obj.DATA, function(indexInArray, value) {
var depts = value[departmentListIndex];
console.log("test",depts);
});
But I'm getting this error:
VM1172:38 Uncaught TypeError: $.each.first is not a function
doing a $.get(obj.DATA)..... doesn't work either.
$.each.first(obj.DATA[0], function(indexInArray, value) {
var depts = value[departmentListIndex];
console.log("test",depts);
});
I'm fairly new to javascript. I retreive data from a sql server database that looks like this :
[Object { shortcode="0013A2004031AC9A", latest_measurement=1067, keyid="6801"},
Object { shortcode="0013A2004031AC9A", latest_measurement=7, keyid="6802"},
Object { shortcode="0013A2004031AC9A", latest_measurement=8598838, keyid="6803"}]
I want to format this in a json like this :
{mac : 0013A2004031AC9A, keys : {6801:1067, 6802:7, 6803:8598838}}
but I just don't get to that.
I have
var jsonDataPerMac = {};
I loop over the json object above and for every new mac I find I do :
jsonDataPerMac[i]={"mac": device.shortcode, "keys":[]};
but how do I get to fill the keys?
Any hints would be appreciated.enter code here
var macs = [];
var jsonDataPerMac = {};
var i = 0;
$.ajax({
url: "/bmmeasurements",
type: "GET",
data: {"unitid" : unitid},
async: false,
success: function (data) {
console.log(data);
initializeTable();
$.each(data, function (index,device) {
//add all distinct macs in an array, to use them as a column header
if($.inArray(device.shortcode, macs) == -1) {
macs.push(device.shortcode);
jsonDataPerMac[i]={"mac": device.shortcode, "keys":[]};
i++;
//create a table cell for each possible key. id = 'mac-key'
createTableGrid(device.shortcode);
}
//add the measurement data to the correct cell in the grid
$('#' + device.shortcode + '-' + device.keyid).html(device.latest_measurement);
});
}});
Here is my proposition. I would rather avoid using jQuery to perform such a simple operations. In this particular example, we use forEach and for..in loop.
//new output array
var newArray = [];
//we traverse the array received from AJAX call
array.forEach(function(el) {
var added = false; // it's false by default
// we check if the mac is already in newArray, if yes - just add the key
for(var i in newArray) {
if(newArray[i].mac == el.shortcode) {
newArray[i].keys.push(el.keyid+":"+el.latest_measurement);
added = true; // tells us whether the key has been added or not
}
}
// if key hasn't been added - create a new entry
if(!added) {
newArray.push({"mac": el.shortcode, "keys":[el.keyid+":"+el.latest_measurement]});
}
});
console.log(newArray);
You can transform above code to a function and then, reuse it in your ajax onSuccess method. Remember to pass the array as an argument and to return newArray.
JSFiddle:
http://jsfiddle.net/2d5Vq/2/
You need to combine the entries first...
var reducedData = {};
$.each(macs, function(index,macitem){
if (reducedData.hasOwnProperty(macitem.shortcode)) {
reducedData[macitem.shortcode].push(macitem.key);
} else {
reducedData[macitem.shortcode] = [ macitem.key ];
}
});
And then map to your desired format inside an array...
var jsonDataPerMac = [],
i = 0;
$.map(reducedData, function(keys,mac){
jsonDataPerMac[i++] = {"mac": mac, "keys": keys};
// your other code goes here
});
Also your usage of jsonDataPerMac suggests that you want it to be an array.
I am trying to build a simple page to view messages saved in a mysql db via JSON and jQuery.
My JSON IS
{"unread_msgs":[{"id":"6","title":"33333","user1":"19","timestamp":"1383747146","client_id":"Generic"},{"id":"5","title":"42142","user1":"19","timestamp":"1383740864","client_id":"Generic"}],"read_msgs":[{"id":"4","title":"test to addnrow","user1":"19","timestamp":"1383676647","client_id":"Generic"},{"id":"2","title":"kll","user1":"19","timestamp":"1383675548","client_id":"Generic"},{"id":"1","title":"jkjljklj","user1":"19","timestamp":"1382539982","client_id":"Generic"}],"urm_t":2,"rm_t":3}
My JS
<script type="text/javascript">
function GetClientMsgs () {
$.post("assets/server/client_msgs.php",{ client_id:local_client_id } ,function(data)
{
var MsgData = $.parseJSON(data);
console.log("Msg json data parsed");
$.each(MsgData, function(key, value)
{
console.log(value);
$('#unread_row').append('<td>'+value.unread_msgs.title+'</td><td>'+value.unread_msgs.studioname+'</td><td>'+value.unread_msgs.timestamp+'</td><td>X</td>');
$('#read_row').append('<td>'+value.read_msgs.title+'</td><td>'+value.read_msgs.studioname+'</td><td>'+value.read_msgs.timestamp+'</td><td>X</td>');
});
});
}
</script>
PHP
$msgs = array('unread_msgs' => $dn1s, 'read_msgs' => $dn2s, 'urm_t' => $unread_msgs, 'rm_t' => $read_msgs);
$json = json_encode($msgs);
I am trying to post values returned such as unread_msgs.title or .id and am not able to access any of the objects. I have searched on here and could not find something specific to my structure. Thanks alot.
I would loop over the unread and read results separately, like this:
$.each(MsgData.unread_msgs, function(key, value)
{
// code append to unread row
console.log(value.id, value.title, "etc");
});
$.each(MsgData.read_msgs, function(key, value)
{
// append to append to read row
console.log(value.id, value.title, "etc");
});
Pasting your json into a formatter such as http://jsonformatter.curiousconcept.com/ can help you to see its structure.
In this row:
$('#unread_row').append('<td>'+value.unread_msgs.title+'</td><td>'+value.unread_msgs.studioname+'</td><td>'+value.unread_msgs.timestamp+'</td><td>X</td>');
You are accessing the value variable as an object, while it is in fact an array.
To access the first unread message id within your $.each loop, you would do: value[0].id.
If you are trying to get a list of unread and read messages, try to loop over them.
$.each(MsgData.unread_msgs, function(index, message) {
$('#unread_row').append('<td>' + message.id + '</td><td>.......');
});
$.each(MsgData.read_msgs, function(index, message) {
$('#read_row').append('<td>' + message.id + '</td><td>.......');
});
Or with a nested loop:
$.each(MsgData, function(key, value) {
$.each(value, function(index, message) {
$('#' + key).append('<td>' + message.id + '</td><td>....);
});
]);
I am making a small Chrome extension. I would like to use chrome.storage but I can't get it to delete multiple items (array) from storage. Single item removal works.
function clearNotes(symbol)
{
var toRemove = "{";
chrome.storage.sync.get(function(Items) {
$.each(Items, function(index, value) {
toRemove += "'" + index + "',";
});
if (toRemove.charAt(toRemove.length - 1) == ",") {
toRemove = toRemove.slice(0,- 1);
}
toRemove = "}";
alert(toRemove);
});
chrome.storage.sync.remove(toRemove, function(Items) {
alert("removed");
chrome.storage.sync.get( function(Items) {
$.each(Items, function(index, value) {
alert(index);
});
});
});
};
Nothing seems to break but the last loop that alerts out what is in the storage still shows all the values I am trying to delete.
When you pass in a string to sync.remove, Chrome will attempt to remove the one single item whose key matches the input string. If you need to remove multiple items, use an array of key values.
Also, you should move your remove call to inside your get callback.
function clearNotes(symbol)
{
// CHANGE: array, not a string
var toRemove = [];
chrome.storage.sync.get( function(Items) {
$.each(Items, function(index, value)
{
// CHANGE: add key to array
toRemove.push(index);
});
alert(toRemove);
// CHANGE: now inside callback
chrome.storage.sync.remove(toRemove, function(Items) {
alert("removed");
chrome.storage.sync.get( function(Items) {
$.each(Items, function(index, value)
{
alert(index);
});
});
});
});
};
Slightly Slimmer and updated solution
chrome.storage.sync.get(null, (data) => {
const keys = Object.keys(data).filter((x) => x.startsWith('<start-of-key>')); // Can replace `startsWith` with regex or any other string comparison
chrome.storage.sync.remove(keys);
});