read json values from ajax success? - javascript

I am getting JSON data like below example. Now I want get each value in separate variables like
var reviewDate ='2015-06-01T05:00:00Z'
var developers ='Ankur Shah,Srikanth Vadlakonda,Tony Liu, Qiuming Jie
var reviewers = 'mike,john'
var title='Test project'
var call =$.ajax({
url:url,
type:"GET",
dataType:"json",
headers:{
Accept:"application/json;odata=verbose"
}
});
call.done(function(data,textStatus,jqXHR){
alert("Success!! "+ jqXHR.responseText);
});
call.fail(function(jqXHR,textStatus,errorThrown){
alert("Error retriving Tasks!! "+ jqXHR.responseText);
});
I am getting results in call.done in . How to set those values?

You could do something along these lines:
http://jsfiddle.net/e0mfc1rd/2/
Javascript:
var data = {
results: {
Date_x0020_of_x0020_Review: '2015-06-01T05:00:00Z',
Name_x0020_of_x0020_Developers: {
results: [
{
__metadata: {},
Title: 'Ankur Shah'
},
{
__metadata: {},
Title: 'Tony Liu'
},
{
__metadata: {},
Title: 'Qiuming Jie'
}
]
},
Name_x0020_of_x0020_Reviewers: {
results: [
{
__metadata: {},
Title: 'Mike'
},
{
__metadata: {},
Title: 'John'
}
]
}
}
}
// map the key names.
// you could do something more clever here, like just extracting
// the segment after the last underscore using substring or a regex,
// but for this example we'll do a simple map.
var names = {
'Name_x0020_of_x0020_Reviewers': 'reviewers',
'Name_x0020_of_x0020_Developers': 'developers'
}
// a variable to hold the result.
var processed = {};
// iterate over each key in data.results
// (e.g. 'Name_x0020_of_x0020_Developers', 'Name_x0020_of_x0020_Reviewers', etc.)
Object.keys(data.results).forEach(function(k) {
// if the object indexed at that key has a 'results' property that is an array...
if (Array.isArray((data.results[k] || {}).results)) {
// pluck the Title attribute from each of those entries into a new array.
var values = data.results[k].results;
var titles = values.map(function(v) {
return v.Title;
});
// translate keys like 'Name_x0020_of_x0020_Reviewers'
// into something more palatable
var key = names[k] || k;
// join the titles into a string, separated by a comma
processed[key] = titles.join(',');
}
else if (k.indexOf('Date') === 0) { // key starts with 'Date'
processed[k] = new Date(data.results[k]);
}
});
After which the variable 'processed' would contain:
{
"Date_x0020_of_x0020_Review": "2015-06-01T05:00:00.000Z",
"developers": "Ankur Shah,Tony Liu,Qiuming Jie",
"reviewers": "Mike,John"
}

You could also use UnderscoreJS to get your data from your JSON.
You need to chain some pluck calls and you should get to your data.
Please find the demo below and here at jsFiddle.
To get the parsed object into your comma separated format just use for example: var developers = parsed.developers.join(',');
var resultJSON = {
d: {
__metadata: {},
"Name_x0020_of_x0020_Developers": {
"results": [{
"Title": "Ankur Shah"
}, {
"Title": "Srikanth"
}, {
"Title": "Tony Liu"
}]
},
"Name_x0020_of_x0020_Reviewers": {
"results": [{
"Title": "Name1"
}, {
"Title": "Name2"
}, {
"Title": "Name3"
}]
}
}
};
//console.log(resultJSON);
var names = {
developers: 'Name_x0020_of_x0020_Developers',
reviewers: 'Name_x0020_of_x0020_Reviewers'
};
var parsed = {};
_.each(names, function (name, key) {
parsed[key] = _.chain(resultJSON) // key is developers, reviewers
.pluck(name) // is the name in the JSON e.g. Name_..._Developers
.pluck('results')
.tap(function (data) { // tap is optional and can be removed
console.log('before flatten', data); // it shows the nesting [[]]
})
.flatten(true) // used to remove outer array
.tap(function (data) {
// we now have the result. Next, get the title
console.log('before getting the Title', data);
})
.pluck('Title')
.value();
});
console.log(parsed);
document.getElementById('output').innerHTML = JSON.stringify(parsed, null, 2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<pre id="output"></pre>

Related

How do I make autocomplete data dynamic?

$(document).ready(function(){
$('input.autocomplete').autocomplete({
data: {
"Apple": null,
"Microsoft": null,
"Google": 'https://placehold.it/250x250'
},
onAutocomplete: function () {
var mobileSearch = $('#SearchM').val();
var desktopSearch = $('#SearchD').val();
if (desktopSearch.length > 0){ //Desktop Search
window.location.href = '/'+desktopSearch;
}
else {
window.location.href = '/'+mobileSearch;
}
}
});
});
I want to get the data from the database and print it here. It's nonsense to write by hand when you have 5000+ data.
data: {
"Apple": null,
"Microsoft": null,
"Google": 'https://placehold.it/250x250'
},
I was able to pull the data from an address with Fetch, but I couldn't print it.
var x = fetch('/alltags')
.then(response => response.json())
.then(data => {
console.log(data);
return data;
});
What can I do ?
The JQuery Autocomplete Widget expects a source property, containing the options to display.
source accepts either an Array, String or Function.
You could map the response from your fetch into an array of objects.
The source array can include strings: [ "Choice1", "Choice2" ]
OR
Objects with label and value properties: [ { label: "Choice1", value: "value1" }, ... ]
For example:
$(document).ready(function(){
$('input.autocomplete').autocomplete({
source: [{
label: "Google",
value: "https://placehold.it/250x250"
} ...],
onAutocomplete: function () {
var mobileSearch = $('#SearchM').val();
var desktopSearch = $('#SearchD').val();
if (desktopSearch.length > 0){ //Desktop Search
window.location.href = '/'+desktopSearch;
}
else {
window.location.href = '/'+mobileSearch;
}
}
});
});

Javascript - Create and populate associative array containing sub arrays

I'm trying to collate some data. I would like to populate an array containing sub arrays, for example, I have some json data that I am iterating over:
{
"name": "name1",
"prices": "209.67"
},
{
"name": "name1",
"prices": "350"
},
{
"name": "name2",
"price": "195.97"
},
I would like to create an array that ends up looking something like the following:
myArray['name1']prices[0] = 209.67,
prices[1] = 350,
['name2']prices[0] = 195.97
I thought that the code below would achieve what I wanted but it doesn't work. It throws an exception. It doesn't seem to recognise the fact that the prices are an array for a given index into the main array. Instead the prices appear at the same level as the names. I want the main array for a given name to contain an inner array of prices.. Does anybody have any idea how I could modify to make this work?
function doStuff() {
var cryptoData = getData();
var datasetValues = {};
datasetValues.names = [];
datasetValues.names.prices = [];
for (var result = 0; result < cryptoData.length; result++) {
var data = cryptoData[result];
if (datasetValues.names.indexOf(data.cryptoname) === -1)
{
datasetValues.names.push(data.cryptoname);
}
// This works
//datasetValues.names.prices.push(data.prices);
// This doesn't!
datasetValues.cryptoNames[data.cryptoname].prices.push(data.prices);
}
}
You could reduce the array by using an object and take a default object if the property is not set. Then push the price.
var data = [{ name: "name1", price: "209.67" }, { name: "name1", price: "350" }, { name: "name2", price: "195.97" }],
result = data.reduce((r, { name, price }) => {
r[name] = r[name] || { name, prices: [] };
r[name].prices.push(+price);
return r;
}, Object.create(null));
console.log(result);
Try this
function parseData(input){
return input.reduce(function(o,i){
o[i.name] = {};
if(!o[i.name]['prices']){
o[i.name]['prices'] = [];
}
o[i.name]['prices'].push(i.prices);
return o;
},{});
}

trouble having sorting an array with underscore.js

Im trying to sort the following list. But i get this:
B
Buller
Bøller
A
Agnes
C
Cara
And I would like this:
A
Agnes
B
Buller
Bøller
C
Cara
I have see it here:
how to display names in alphabetical groups in Handlebarsjs underscorejs
Any help would be very nice ....
var series =
[
{ slug: "et", title: "Buller" },
{ slug: "fem", title: "Bøller" },
{ slug: "to", title: "Agnes" },
{ slug: "tre", title: "Cara" }
];
function sortByName (array){
return _.sortBy(array, "title");
}
groupedContacts = _.groupBy(series, function(contact){
return contact.title.substr(0,1);
});
_.each(groupedContacts, function (series, key) {
console.log(key); // writes the Index letter
// optional sort
var sortedContacts = _.sortBy(series, function (contact) {
return contact.title;
});
_.each(sortedContacts, function(contact) {
// Writes the contact name
console.log(contact.title);
});
});
Why you need to do grouping if you want to do sorting. Remove the following code
groupedContacts = _.groupBy(series, function(contact){
return contact.title.substr(0,1);
});
_.each(groupedContacts, function (series, key) {
console.log(key); // writes the Index letter
// optional sort
var sortedContacts = _.sortBy(series, function (contact) {
return contact.title;
});
_.each(sortedContacts, function(contact) {
// Writes the contact name
console.log(contact.title);
});
});
and just use sortBy.
var series = [
{ slug: "et", title: "Buller" },
{ slug: "fem", title: "Bøller" },
{ slug: "to", title: "Agnes" },
{ slug: "tre", title: "Cara" }
];
var sorted = _.sortBy(series, 'title');
document.getElementById('sorted').innerHTML = JSON.stringify(sorted);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<div id="sorted"></div>

creating Multi-dimentional array and JSON parsing

i have a fiddle here http://jsfiddle.net/prantikv/eqqd6xfm/3/
i have data as such
var info={
"company1":[
{"employee":"*2"},
{"rooms":"*6"},
{"vehicals":"3"},
],
"company2":[
{"employee":"*2"},
{"rooms":"*6"},
{"vehicals":"3"},
],
"company3":[
{"employee":"*2"},
{"rooms":"*6"},
{"vehicals":"3"},
]
i get the data from an a json file.
what i want to do is that i want to create individial company variables so that i can load them up quickly without other company data
so what i do is this
var companiesArray=[];
for(company in info){
console.log("company--> "+company);//company1,2,etc
var detailsArray=[];
for(var i=0;i<info[company].length;i++)
{
//loop through the inner array which has the detials
for(var details in info[company][i]){
var detailsValue=info[company][i][details];
detailsArray[details]=detailsValue;
}
}
companiesArray[company]=[company,detailsArray];
}
console.log(companiesArray);
so when i try to get the data i have to do something like this
companiesArray['company1'][1].employee
what i want to do is this
companiesArray['company1'].employee
where am i going wrong?
If You don't want to /cannot change the JSON, simply change
detailsArray = []
to
detailsObject = {}
and
companiesArray[company]=[company,detailsArray];
to
companiesArray[company]=detailsObject;
Now you can use
companiesArray['company1'].employee
You have to form your json like this:
var info={
"company1": {
"employee":"*2",
"rooms":"*6",
"vehicals":"3"
},
"company2": {
"employee":"*2",
"rooms":"*6",
"vehicals":"3"
},
"company3": {
"employee":"*2",
"rooms":"*6",
"vehicals":"3"
}
};
Use curly braces ({}) instead of brackets ([]) in order to create objects accessible with the dot notation like this:
info.company1.employee
I agree with #Pavel Gatnar and #Guillaume. This is a very bad data structure. If you can't change the structure only then should you use the following code.
var info = {
"company1": [{
"employee": "*2"
}, {
"rooms": "*6"
}, {
"vehicals": "3"
}],
"company2": [{
"employee": "*2"
}, {
"rooms": "*6"
}, {
"vehicals": "3"
}],
"company3": [{
"employee": "*2"
}, {
"rooms": "*6"
}, {
"vehicals": "3"
}]
};
var companies = {},
companyNames = Object.keys(info);
companyNames.forEach(function (companyName) {
var companyInfo = info[companyName],
company = {};
companyInfo.forEach(function (properties) {
var innerPropertyName = Object.keys(properties);
innerPropertyName.forEach(function (property) {
company[property] = properties[property];
});
});
companies[companyName] = company;
});
console.log(companies);
check out the fiddle here
Try this:
var info={
"company1":[
{"employee":"*2"},
{"rooms":"*6"},
{"vehicals":"3"},
],
"company2":[
{"employee":"*2"},
{"rooms":"*6"},
{"vehicals":"3"},
],
"company3":[
{"employee":"*2"},
{"rooms":"*6"},
{"vehicals":"3"},
]
};
var companiesArray = {};
for(company in info){
var detailsArray = {};
for(var i=0;i<info[company].length;i++) {
for(var details in info[company][i]){
var detailsValue=info[company][i][details];
detailsArray[details]=detailsValue;
}
}
companiesArray[company]=detailsArray;
}
console.log(companiesArray['company1'].employee);

javascript how to count the object and combin

I get the data from database like this:
var json = [
{
name: "one",
roles: [
{ role: "admin",state: 1 },
{ role: "operator",state: 1 },
{ role: "admin",state: 1 }
]
},
{
name: "two",
roles: [
{ role: "admin2",state: 0 },
{ role: "operator",state: 1 },
{ role: "admin",state: 1 }
]
}
];
And I want to become this
=>
var json = [
{
name: "one",
roles:[...],
data: [
{ "admin": 2,"eable": 2,"disable":0 },
{ "operator": 1,"eable": 1,"disable":0}
]
},
{
name: "two",
roles:[...],
data: [
{ "admin": 1,"eable": 0,"disable":1 },
{ "admin2": 1,"eable": 1,"disable":0},
{ "operator": 1,"eable": 1,"disable":0}
]
}
];
I'm getting stuck now, don't know what to do,please help.
Here is what I tried:
json.forEach(function(v,k){
var ret = {
"enable":0,
"disable":0
}
json[k]['data'] = [];
json[k]['roles'].forEach(function(v,k){
json[k]['data'].push( v['role'] );
})
});
http://jsfiddle.net/B9XkX/1/
This is a lot to chew on because the data structure is weird but bear with me:
result = json.map(function(obj){
// we can use map here to transform each object, whatever we return will
// go into the result array.
var roles = obj.roles.reduce(function(memo, item){
// we need to turn a role object into a data object
// but because we are counting the number of eable
// and disable states we need to make a discreet object
// that can hold the numbers without worrying about the
// final data structure.
memo[item.role] = memo[item.role] || {};
memo[item.role].eable = memo[item.role].eable || 0;
memo[item.role].disable = memo[item.role].disable || 0;
// we initialize the memo object if we haven't seen the
// role before.
if (item.state === 1) {
// we count eable for one state
memo[item.role].eable += 1;
} else if (item.state === 0) {
// we count disable for the other state
memo[item.role].disable += 1;
}
return memo;
}, {});
// now the roles object looks something like this:
/**
* {
* admin: {eable: 2, disable: 0},
* operator: {eable: 1, disable: 0}
* }
**/
return {
name: obj.name,
roles: obj.roles,
data: Object.keys(roles).map(function(key){
// now we need to turn the roles object back into an array, so we use
// Object.keys method to turn the keys on the roles object into an array
// and we use map again to setup an object that we will use instead.
var item = {};
item[key] = 1; // {admin: 1}
item.eable = roles[key].eable; // {admin:1, eable: 2}
item.disable = roles[key].disable; // {admin:1, eable: 2, disable: 0}
return item;
})
}
});

Categories

Resources