autocomplete is not working with json - javascript

What I need:
append the data in array, then push in autocomplete js.
json:
{
"industry": [
{
"id": 16,
"name": "Agriculture & Forestry",
"industry_url": "agriculture-forestry"
},
{
"id": 3,
"name": "Apparel & Clothing",
"industry_url": "apparel-fashion"
},
{
"id": 56,
"name": "Architecture & Designing",
"industry_url": "architecture"
},
{
"id": 83,
"name": "Astrology",
"industry_url": "astrology"
}
]
}
code:
if (http.readyState == 4 && http.status == 200)
{
if (obj = JSON.parse(http.responseText), obj.industry.length > 0)
{
industry = document.getElementById("industry_url").getAttribute("value");
var industry = [];
for (var b = 0; b < obj.industry.length; b++)
{
//console.log(obj.industry[b]);
var indus=obj.industry[b];
var temp = new Object();
temp["name"] = indus.name;
temp["event_url"] = indus.industry_url;
industry.push(temp);
console.log(industry);
$('.autocomplete').autocomplete({
lookup: industry,
onSelect: function(suggestion) {
var thehtml = '<strong>industry name:</strong> ' + suggestion.name + ' <br> <strong>'+ suggestion.industry_url+'</strong>';
$('#outputcontent').html(thehtml);
}
});
html:
<input type="text" autocomplete="off" name="Industry" id="industry_name"
class="biginput autocomplete" placeholder="All Industry" id="ex3">
I have tried to google and find the jquery library.
Logic I found that is data would push in array first the push that array in autocomplete.
i have taken help from How do I pass this JSON data to an autocomplete
final code that i have dig but its also not working
$(document).ready(function(){
var arrayAutocomplete = new Array();
$.getJSON('apiurl', function(json)
{
console.log(json);
$.each(json.country,function(index, value){
console.log(value);
arrayAutocomplete = new Array();
arrayAutocomplete['text'] = value.text;
arrayAutocomplete['country_url'] = value.country_url;
});
$("#country_name").autocomplete({source: arrayAutocomplete});
});
});

Related

Looping through items in an object for google sheets

I am trying to loop through an array that is part of a JSON object from a page speed insights call to add all of the unused javascript Urls to a google sheet using the script editor.
Here is an example of the JSON object:
"audits": {
"unused-javascript": {
"id": "unused-javascript",
"title": "Remove unused JavaScript",
"description": "Remove unused JavaScript to reduce bytes consumed by network activity. [Learn more](https://web.dev/unused-javascript/).",
"score": 0.43,
"scoreDisplayMode": "numeric",
"numericValue": 1350,
"numericUnit": "millisecond",
"displayValue": "Potential savings of 231 KiB",
"details": {
"type": "opportunity",
"headings": [
{
"key": "url",
"valueType": "url",
"subItemsHeading": {
"key": "source",
"valueType": "code"
},
"label": "URL"
},
{
"key": "totalBytes",
"valueType": "bytes",
"subItemsHeading": {
"key": "sourceBytes"
},
"label": "Transfer Size"
},
{
"key": "wastedBytes",
"valueType": "bytes",
"subItemsHeading": {
"key": "sourceWastedBytes"
},
"label": "Potential Savings"
}
],
"items": [
{
"url": "https://connect.facebook.net/signals/config/1926350194273730?v=2.9.2=stable",
"totalBytes": 140229,
"wastedBytes": 108197,
"wastedPercent": 77.15757011763822
},
{
"url": "https://static.example.com/domain.us.modern.bundle.a02fef045566caf5d464.js",
"totalBytes": 306716,
"wastedBytes": 106243,
"wastedPercent": 34.63892414884589
},
{
"url": "https://www.googletagmanager.com/gtm.js?id=GTM-KZ",
"totalBytes": 127214,
"wastedBytes": 21845,
"wastedPercent": 17.17151000374831
}
],
"overallSavingsMs": 1350,
"overallSavingsBytes": 236285
}
},
I am attempting to loop through the "items" array within the "unused-javascript" object and get all of the urls to show in google sheets.
Here is the code I have within the script editor. When I run this, only one URL shows on the sheet. However, I am trying to get all of the URLs added to the sheet.
function pageSpeed(Url) {
var key = "AIzaSyAyHY";
var serviceUrl = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=" + Url + "&key=" + key;
var array = [];
if (key == "YOUR_API_KEY")
return "Please enter your API key to the script";
var response = UrlFetchApp.fetch(serviceUrl);
if (response.getResponseCode() == 200) {
var content = JSON.parse(response.getContentText());
if ((content != null) && (content["lighthouseResult"] != null)) {
if (content["captchaResult"]) {
var timetointeractive = content["lighthouseResult"]["audits"]["interactive"]["displayValue"].slice(0, -2);
var firstcontentfulpaint = content["lighthouseResult"]["audits"]["first-contentful-paint"]["displayValue"].slice(0, -2);
var firstmeaningfulpaint = content["lighthouseResult"]["audits"]["first-meaningful-paint"]["displayValue"].slice(0, -2);
var speedindex = content["lighthouseResult"]["audits"]["speed-index"]["displayValue"].slice(0, -2);
var unusedJs = content["lighthouseResult"]["audits"]["unused-javascript"]["details"]["items"];
for (var i = 0; i < unusedJs.items.length; i++) {
var unusedUrl;
unusedUrl = unusedJs[i]["url"]
}
}
else {
var timetointeractive = "An error occured";
var firstcontentfulpaint = "An error occured";
var firstmeaningfulpaint = "An error occured";
var speedindex = "An error occured";
var unusedJs = "An error occured";
}
}
var currentDate = new Date().toJSON().slice(0, 10).replace(/-/g, '/');
array.push([timetointeractive, firstcontentfulpaint, firstmeaningfulpaint, speedindex, currentDate, "complete", unusedUrl]);
Utilities.sleep(1000);
return array;
}
}
Any and all help is appreciated!
You're on the right track.
Take a look below at my usage of Array.prototype.map. That's the simpler route.
Your for loop would work just as well IF you declared unusedUrl outside of (ie. before) the loop AND pushed to an existing array. As it is, there's an issue of scope, so unusedUrl is redeclared on every iteration, meaning you'll only assign the last iteration's value to unusedUrl.
Both solutions are below.
Using map
var content = {
lighthouseResult: {
audits: {
'unused-javascript': {
// Other stuff
details: {
// Other stuff
items: [
{
url:
'https://connect.facebook.net/signals/config/1926350194273730?v=2.9.2=stable',
totalBytes: 140229,
wastedBytes: 108197,
wastedPercent: 77.15757011763822,
},
{
url:
'https://static.example.com/domain.us.modern.bundle.a02fef045566caf5d464.js',
totalBytes: 306716,
wastedBytes: 106243,
wastedPercent: 34.63892414884589,
},
{
url: 'https://www.googletagmanager.com/gtm.js?id=GTM-KZ',
totalBytes: 127214,
wastedBytes: 21845,
wastedPercent: 17.17151000374831,
},
],
overallSavingsMs: 1350,
overallSavingsBytes: 236285,
},
},
},
},
}
var items = content.lighthouseResult.audits['unused-javascript'].details.items
var unusedUrls = items.map(item => item.url) // OR, using es6, items.map(({ url }) => url)
console.log(unusedUrls)
Using for
var items = content.lighthouseResult.audits['unused-javascript'].details.items
var unusedUrls = []
for (var i = 0; i < items.length; i++) {
unusedUrls.push(items[i]['url'])
}

Nested Pointer Data

I'm calling the below Parse Query using the Parse Server Javascript API. I have a class called Device, which has a pointer object to Device_Type which in turn has a pointer to Manufacturer.
I can successfully display the deviceID in inventoryItem, but get undefined for manufacturer, despite there being the relevant data in the JSON network return.
$scope.getDeviceItems = function () {
var query = new Parse.Query("Device");
query.include("Device_Type");
query.include("Device_Type.Manufacturer");
query.find({
success: function (results) {
$scope.deviceItems = [];
for (i = 0; i < results.length; i++) {
var d = results[i].get("Device_Type");
var m = results[i].get("Device_Type.Manufacturer");
var inventoryItem = {
deviceID: d.get("Device_ID"),
manufacturer: m.get("Manufacturer_Name")
}
};
};
};
};
How would I correctly obtain the nested pointer data into manufacturer?
Here's a sample JSON Object:
{
"results": [{
"objectId": "q3D2myHG3e",
"createdAt": "2017-07-30T22:28:05.035Z",
"updatedAt": "2017-09-19T20:40:05.580Z",
"Device_Type": {
"objectId": "Ksej3F2sdp5",
"Device_Name": "Device 1",
"createdAt": "2017-07-30T21:57:58.638Z",
"updatedAt": "2017-08-08T20:20:14.397Z",
"Manufacturer": {
"objectId": "3NahYBNIiC",
"Manufacturer_Name": "ABC Ltd",
"createdAt": "2017-07-30T21:56:40.557Z",
"updatedAt": "2017-07-30T22:13:07.425Z",
"Devices": {
"__type": "Relation",
"className": "DeviceType"
},
"__type": "Object",
"className": "DeviceManufacturer"
},
"__type": "Object",
"className": "DeviceType"
},
...
}]
}
$scope.getDeviceItems = function () {
var query = new Parse.Query("Device");
query.include("Device_Type");
query.include("Device_Type.Manufacturer");
query.find({
success: function (results) {
$scope.deviceItems = [];
for (i = 0; i < results.length; i++) {
var curResult = results[i];
var d = curResult.Device_Type;
var m = curResult.Device_Type.Manufacturer;
var inventoryItem = {
deviceID: d.Device_ID
manufacturer: m.Manufacturer_Name
}
};
};
};
};
Not sure why a map is being used a regular JS object as shown above would work easier (assuming find function just resolved with the JS object from parsing the JSON instead of turning it into a Map object)
Using a Map you need to call get twice as far as I can tell to resolve "deeper" keys.
$scope.getDeviceItems = function () {
var query = new Parse.Query("Device");
query.include("Device_Type");
query.include("Device_Type.Manufacturer");
query.find({
success: function (results) {
$scope.deviceItems = [];
for (i = 0; i < results.length; i++) {
var curResult = results[i];
var d = curResult.get('Device_Type');
var m = curResult.get('Device_Type').get('Manufacturer'); // or d.get('Manufacturer')
var inventoryItem = {
deviceID: d.get('Device_ID')
manufacturer: m.get('Manufacturer_Name')
}
};
};
};
};
var testObj = new Map();
testObj.set('a', new Map());
testObj.get('a').set('b', 4);
console.log(testObj.get('a').get('b'))

option selects from json object on categories

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>

How to get objects with same key values with comma separated

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
)

Use conditional inside $.each function to create array

I want to iterate over the elements of an array and if a condition is true I want to create a new array.
Example: I have an array called Messages whose elements are objects and I want to check if the id attribute equals 5. If yes create a new array only consisting of this object.
messages = [{
"id": 10,
"body": "hello!"
}, {
"id": 21,
"body": "hola!"
}, {
"id": 5,
"body": "ciao!"
}];
var message5 = [];
var dataObj = {};
$.each(messages, function(index, value) {
if (value.id == 5) {
dataObj[index] = value;
}
});
message5.push(dataObj[index]);
I want my result to be:
message5 = [
{
"id": 5,
"body": "ciao!"
}
]
Try to use Array.prototype.filter at this context,
var message5 = messages.filter(function(itm){
return itm.id == 5;
});
console.log(message5); //[{"id": 5,"body": "ciao!"}]
If you want it to be more concise then you could use ES6 Arrow function,
var message5 = messages.filter(itm => itm.id == 5);
console.log(message5); //[{"id": 5,"body": "ciao!"}]
But note that, the above code is similar to,
var message5 = messages.filter(function(itm){
return itm.id == 5;
}.bind(this)); //Arrow function will automatically bind its lexical scope to it.
try to use filter:
var messages = [{
"id": 10,
"body": "hello!"
}, {
"id": 21,
"body": "holla!"
}, {
"id": 5,
"body": "ciao!"
}];
var message5 = messages.filter(function(message) {
return message.id == 5;
});
alert(JSON.stringify(message5));
try
var newArr = messages.filter( function(value){
return value.id == 5;
} );
Use Array filter() method
messages.filter(function(msg){return msg['id'] === 5})
An approach completely in jQuery could be:
$(function () {
var messages = [{
"id": 10,
"body": "hello!"
}, {
"id": 21,
"body": "holla!"
}, {
"id": 5,
"body": "ciao!"
}];
var dataObj = [];
$.each(messages, function (index, value) {
if (value.id == 5) {
dataObj.push(messages[index]);
}
});
$('#result').text(JSON.stringify(dataObj, 4, 4));
});
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<textarea id="result" style="width: 250px;height: 100px"></textarea>

Categories

Resources