I have an array that looks like this
array_names = [Mathew,Kelp ,Liman Kolf, Hebert,Ansh];
Now in the array above, Mathew, Kelp is one name , Liman Kolf is another name and Herbet,Ansh is another name making it 3 names in the array.
Now i want to split this array on new lines in table like below
Mathew,Kelp
Liman Kolf
Herbet,Ansh
But with my code as shown below, the table is represented like this
Mathew
Kelp
Liman Kolf
Herbet
Ansh
JS
//how i save to localstorage
$("#myTableID").on("click", "#add-contact", function() {
var values = [];
value = jQuery(this).closest('tr').find('#user-id').text();
values.push(value);
localStorage.setItem('contact_list', values);
}
var array_names = localStorage.getItem('contact_list').split(',');
if(array_names.length)
{
$.each(array_names, function(index, value){
$('#myTableID2').append('<tr><td id="contact">'+value+'</td></tr>');
});
}
Controller
$contacts = Contact::where('firstname','LIKE','%'.$q.'%')->orWhere('lastname','LIKE','%'.$q.'%')->get();
You should split them by a RegExp
const string = 'Mathew,Kelp ,Liman Kolf, Hebert,Ansh';
const array = string.split(/(?: ,)|(?:, )/)
// ["Mathew,Kelp", "Liman Kolf, Hebert,Ansh"]
As suggested by #Khauri, use JSON.stringify() and JSON.parse() to read/write from/to localStorage:
// save values to localStorage
localStorage.setItem('contact_list', JSON.stringify(values));
// retrive values from localStorage
var array_names = JSON.stringify(localStorage.getItem('contact_list'));
// do things with the values
if (array_names.length) {
$.each(array_names, function (index, value) {
$('#myTableID2').append('<tr><td id="contact">' + value + '</td></tr>');
});
}
Related
Json Array Object
Through Ajax I will get dynamic data which is not constant or similar data based on query data will change. But I want to display charts so I used chartjs where I need to pass array data. So I tried below code but whenever data changes that code will break.
I cannot paste complete JSON file so after parsing it looks like this
[{"brand":"DUNKIN' DONUTS KEURIG","volume":1.9,"value":571757},{"brand":"MC CAFE","volume":1.1,"value":265096}];
You can use Object.keys and specify the position number to get that value
var valueOne =[];
var valueTwo = [];
jsonData.forEach(function(e){
valueOne.push(e[Object.keys(e)[1]]);
valueTwo.push(e[Object.keys(e)[2]]);
})
It seems like what you're trying to do is conditionally populate an array based the data you are receiving. One solution might be for you to use a variable who's value is based on whether the value or price property exist on the object. For example, in your forEach loop:
const valueOne = [];
jsonData.forEach((e) => {
const val = typeof e.value !== undefined ? e.value : e.average;
valueOne.push(val);
})
In your jsonData.forEach loop you can test existence of element by using something like:
if (e['volume']===undefined) {
valueone.push(e.price);
} else {
valueone.push(e.volume);
}
And similar for valuetwo...
You could create an object with the keys of your first array element, and values corresponding to the arrays you are after:
var data = [{"brand":"DUNKIN' DONUTS KEURIG","volume":1.9,"value":571757},{"brand":"MC CAFE","volume":1.1,"value":265096}];
var splitArrays = Object.keys(data[0]).reduce((o, e) => {
o[e] = data.map(el => el[e]);
return o;
}, {});
// show the whole object
console.log(splitArrays);
// show the individual arrays
console.log("brand");
console.log(splitArrays.brand);
console.log("volume");
console.log(splitArrays.volume);
// etc
I'm trying to iterate over this json encoded array which is a string:
"{"":{"count":{"total":112,"open":0,
"solved":0,
"deleted":106,
"closed":6},
"average_time_open_in_minutes":206,
"tickets_fortnight_week_count":11,
"tickets_last_week_count":15,"trend":1},
"Net2grid":{"count":"total":8,"open":0,"solved":0,"deleted":8},"average_time_open_in_minutes":0,"tickets_fortnight_week_count":0,"tickets_last_week_count":0,"trend":0},"Closed_by_merge":{"count":{"total":2,"open":0,"solved":0,"closed":2},"average_time_open_in_minutes":502,"tickets_fortnight_week_count":0,"tickets_last_week_count":0,"trend":0},"Analytics":{"count":{"total":1,"open":0,"solved":0,"deleted":1},"average_time_open_in_minutes":26,"tickets_fortnight_week_count":0,"tickets_last_week_count":0,"trend":0},"Meter":{"count":{"total":5,"open":5,"solved":0},"average_time_open_in_minutes":0,"tickets_fortnight_week_count":0,"tickets_last_week_count":2,"trend":1},"Installation":{"count":{"total":8,"open":5,"solved":3},"average_time_open_in_minutes":404,"tickets_fortnight_week_count":0,"tickets_last_week_count":0,"trend":0},"Other...":{"count":{"total":3,"open":2,"solved":1},"average_time_open_in_minutes":39,"tickets_fortnight_week_count":0,"tickets_last_week_count":0,"trend":0},"Meter Offline":{"count":{"total":8,"open":7,"solved":1},"average_time_open_in_minutes":8,"tickets_fortnight_week_count":0,"tickets_last_week_count":0,"trend":0},"App Usage":{"count":{"total":6,"open":5,"solved":0,"deleted":1},"average_time_open_in_minutes":8,"tickets_fortnight_week_count":0,"tickets_last_week_count":0,"trend":0}}"
An ajax call returns that string and i'm trying to only get the keys like: "app usage" and "Meter Offline" to return like so:
$.get('/ajax/ticket-and-notes-data.php', function (data) {
var problems = getProblems(data);
function getProblems(problems) {
var problemCategories = [];
$.each(JSON.parse(problems), function (key, value) {
if (key != "") {
problemCategories.push = key;
}
});
return problemCategories;
}
});
But I can't get the keys to go into the problemCategories.
I use this to set the categories in a highchart bubble chart and I will use more of the data from the string later.
I need to get this to work first.
The issue is in the way that you're using array.push. You should use array.push(item) instead of array.push = item.
This is my JSON, I want to directly get the zipCodes values from the JSON without looping through the JSON. How can I do it?
countries:[
{
name:'India',
states:[{
name:'Orissa',
cities:[{
name:'Sambalpur',
zipCodes:{'768019','768020'}
}]
}]
}
]
I think you are looking for
countries[0].states[0].cities[0].zipCodes
Please note, this works for the above JSON as there is only 1 country in countries array and same as for states and cities. However, if there are more than 1 country, state or city then, you will have to iterate to extract information until and unless you know the exact index.
As this is not an associative array, your option is only to use indexes like this:
countries[x].states[y].cities[0].zipCodes
Where x would be each representation of state in your array, in case, of course, that you have more than one.
Similarly y would be each state in each state in each country, in case you have more of those and you can do the same for cities if you need to.
EDIT:
Here's how you can iterate the array:
for(var c in countries)
{
var name = countries[c].name;
if (name === "CountryIAmLookingFor")
{
var statesList = countries[c].states;
for (var s in statesList)
{
var stateName = statesList[s].name;
.....
}
}
}
You can keep iterating until you find the country, state, and city you need, then extract the zipCodes from there as shown in the previous code snippet.
Without "looping"
You can do this crazy trick (not saying this is the best way, but this way you aren't looping through the JSON):
var myData = { 'Put Your Data': 'HERE' };
function getCodes(name, data) {
var sv = data.match(new RegExp(name+'([\\S\\s]*?}][\\S\\s]*?}])'))[1].match(/zipCodes":\[(.*?)\]/g), r = [];
sv.forEach(function (item) {
item.match(/\d+/g).forEach(function (sub) {
r.push(+sub);
});
});
return r;
}
getCodes('India', JSON.stringify(myData));
If your data is already string, then you don't need the JSON.stringify. The forEach you see isn't actually "looping" through the JSON. It's already extracted the zip codes and the code just adds the zip codes to the array. . This line:
var sv = JSON.stringify(data).match(new RegExp(name+'([\\S\\s]*?}][\\S\\s]*?}])'))[1].match(/zipCodes":\[(.*?)\]/g), r = [];
is what grabs the zip codes, it gets something like:
["zipCodes":["768019","768020"]"]
The next line:
item.match(/\d+/g)
will grab the numbers outputting something like:
["768019", "768020"]
The loop just adds the zip-codes to another array
With looping
You're better off looping through the JSON:
var myData = {}, // Your data
zips = [];
myData.countries.forEach(function(i) {
if (i.name === 'India') {
i.states.forEach(function(j) {
j.cities.forEach(function(l) {
l.zipCodes.forEach(function(m) {
zips.push(m);
});
});
});
}
});
//use "zips" array
PERFORMANCE AND SPEED TESTS
After testing copying an array about 500MB (half a gig) took about 30 seconds. That's a lot. Considering an extremely large JSON would be about ~5MB, looping through a little over 5MB of JSON takes about 0.14 seconds. You should never worry about speed.
Here's my "trick" for avoiding explicit iteration. Let JSON.parse or JSON.stringify do the work for you. If your JSON is in string form, try this:
var array = [];
JSON.parse(jsonString, function (key, value) {
if (key === "zipCodes") {
array = array.concat(value);
}
return value;
});
console.log(array); // all your zipCodes
Suppose your Json is like
countries =[
{
name:'India',
states:[{
name:'Orissa',
cities:[{
name:'Sambalpur',
zipCodes:768019768020
}]
},{
name:'mumbai',
cities:[{
name:'rea',
zipCodes:324243
}]
}]
}
]
So now we use MAP it will give you ZipCode of every cities
countries.map(function(s){
s.states.map(function(c){
c.cities.map(function(z){
console.log(z.zipCodes)
})
})
})
OR
If you use return statement then it will give you 2 array with two zip code as per over JSON
var finalOP = countries.map(function(s){
var Stalist = s.states.map(function(c){
var zip = c.cities.map(function(z){
return z.zipCodes
})
return zip
})
return Stalist
})
console.log(finalOP)
I have an object which comes back as part of a return data from a REST server. It is part of an item object.
(I don't have control over the REST server so I can't change the data received):
{
"Option:Color":"Red,Green,Blue,Orange",
"Option:Size":"Small,Medium,Large"
}
What I want to end up with is some control over this, so that I can display the results when a product is selected in my app. It will appear in a modal. I am using Marionette/Backbone/Underscore/JQuery etc. but this is more of a JavaScript question.
I have tried multiple ways of getting at the data with no success. I would like to be able to have the options in a nested array, but I'd be open to other suggestions...
Basically this kind of structure
var Color=('Red', 'Green', 'Blue', 'Orange')
var Size('Small', 'Medium', 'Large')
The Object structure is fine, just need to be able to translate it to an array and take out the 'Option' keyword
Important to mention that I have no idea what the different options might be when I receive them - the bit after Options: might be any form of variation, color, size, flavour etc.
Loop through the parsed JSON and create new keys on a new object. That way you don't have to create the var names yourself; it's automatically done for you, albeit as keys in a new object.
var obj = {
"Option:Color":"Red,Green,Blue,Orange",
"Option:Size":"Small,Medium,Large"
}
function processObj() {
var newObj = {};
for (var k in obj) {
var key = k.split(':')[1].toLowerCase();
var values = obj[k].split(',');
newObj[key] = values;
}
return newObj;
}
var processedObj = processObj(obj);
for (var k in processedObj) {
console.log(k, processedObj[k])
// color ["Red", "Green", "Blue", "Orange"], size ["Small", "Medium", "Large"]
}
Edit: OP I've updated the code here and in the jsfiddle to show you how to loop over the new object to get the keys/values.
Fiddle.
var json = {
"Option:Color":"Red,Green,Blue,Orange",
"Option:Size":"Small,Medium,Large"
};
var color = json['Option:Color'].split(',');
var size = json['Option:Size'].split(',');
Try this to do get a solution without hardcoding all the option names into your code:
var x = {
"Option:Color":"Red,Green,Blue,Orange",
"Option:Size":"Small,Medium,Large"
};
var clean = {};
$.each(x, function(key, val){ //iterate over the options you have in your initial object
var optname = key.replace('Option:', ''); //remove the option marker
clean[optname] = val.split(","); //add an array to your object named like your option, splitted by comma
});
clean will contain the option arrays you want to create
EDIT: Okay, how you get the names of your object properties like "color", which are now the keys in your new object? Thats the same like before, basically:
$.each(clean, function(key, val){
//key is the name of your option here
//val is the array of properties for your option here
console.log(key, val);
});
Of course we stick to jQuery again. ;)
I've got some JSON data that is giving me a list of languages with info like lat/lng, etc. It also contains a group value that I'm using for icons--and I want to build a legend with it. The JSON looks something like this:
{"markers":[
{"language":"Hungarian","group":"a", "value":"yes"},
{"language":"English", "group":"a", "value":"yes"},
{"language":"Ewe", "group":"b", "value":"no"},
{"language":"French", "group":"c", "value":"NA"}
]}
And I want to "filter" it to end up like this:
{"markers":[
{"group":"a", "value":"yes"},
{"group":"b", "value":"no"},
{"group":"c", "value":"NA"}
]}
Right now I've got this, using jQuery to create my legend..but of course it's pulling in all values:
$.getJSON("http://127.0.0.1:8000/dbMap/map.json", function(json){
$.each(json.markers, function(i, language){
$('<p>').html('<img src="http://mysite/group' + language.group + '.png\" />' + language.value).appendTo('#legend-contents');
});
});
How can I only grab the unique name/value pairs in the entire JSON object, for a given pair?
I'd transform the array of markers to a key value pair and then loop that objects properties.
var markers = [{"language":"Hungarian","group":"a", "value":"yes"},
{"language":"English", "group":"a", "value":"yes"},
{"language":"Ewe", "group":"b", "value":"no"},
{"language":"French", "group":"c", "value":"NA"}];
var uniqueGroups = {};
$.each(markers, function() {
uniqueGroups[this.group] = this.value;
});
then
$.each(uniqueGroups, function(g) {
$('<p>').html('<img src="http://mysite/group' + g + '.png\" />' + this).appendTo('#legend-contents');
});
or
for(var g in uniqueGroups)
{
$('<p>').html('<img src="http://mysite/group' + g + '.png\" />' + uniqueGroups[g]).appendTo('#legend-contents');
}
This code sample overwrites the unique value with the last value in the loop. If you want to use the first value instead you will have to perform some conditional check to see if the key exists.
How about something more generic?
function getDistinct(o, attr)
{
var answer = {};
$.each(o, function(index, record) {
answer[index[attr]] = answer[index[attr]] || [];
answer[index[attr]].push(record);
});
return answer; //return an object that has an entry for each unique value of attr in o as key, values will be an array of all the records that had this particular attr.
}
Not only such a function would return all the distinct values you specify but it will also group them if you need to access them.
In your sample you would use:
$.each(getDistinct(markers, "group"), function(groupName, recordArray)
{ var firstRecord = recordArray[0];
$('<p>').html('<img src="http://mysite/group' + groupName+ '.png\" />' + firstRecord.value).appendTo('#legend-contents');
}
See this-
Best way to query back unique attribute values in a javascript array of objects?
You just need a variation that checks for 2 values rather than 1.
var markers = _.uniq( _.collect( markers , function( x ){
return JSON.stringify( x );
}));
reference