I have results from a Google Geocoder request and I need a value form them to go into another array as follows:
var data = {};
Array.each(results, function(loc)
{
data.['value'] = loc.formatted_address;
}
I need data to then contain this structure:
data = [
{value: 'location one'},
{value: 'location two'},
{value: 'location three'}
];
An example of the JSON results from the query here:
http://maps.googleapis.com/maps/api/geocode/json?address=new%20york&sensor=false
In the case of the example query above the output I want is:
data = [
{value: 'New York, NY, USA'},
{value: 'Manhattan, New York, NY, USA'}
];
Im quite confused about what needs to happen in the Array.each function.
Any help would be great, thanks.
Assuming results contains the results array inside the JSON object above:
var data = [];
for(i = 0; i < results.length; i++)
data.push({'value': results[i].formatted_address});
If results contains the whole JSON object though then you need to write:
results = results.results;
before that loop.
Related
I'm trying to structure my data in Swift and I'm having a hard time initializing an the empty array of nested tuples and arrays.
I'm new to Swift, very familiar with JS.
Here is how my data would be structured in JS:
let data = [] // Loop will push objects into this variable
// This is the object that would be pushed into data from within a loop - for range in ranges
ranges.forEach(range => {
data.push({
[range]: {
'minDate': Date(),
'minDateText': '',
'tags': [{
'name': '',
'color': '',
'total': ''
}]
}
});
});
I've tried a few different things in swift, but I'm just not getting it. Seems like you have to have an exact representation of the array before its actually holding any data. I need to initialize it without any data.
The latest thing I've tried is this:
var data:[(String:(String:Date, String:String, String:[(String:String, String:String, String:String)]))] = []
// Get error "Cannot create a single-element tuple with an element label"
You should stop thinking how to code in JS and start reading about how to code in Swift. You can start with Apple Swift book, it covers almost everything you need to get started. So what you really need is to structure your data:
struct Object {
let minDate: Date
let minDateText: String
let tags: [Tag]
}
struct Tag {
let name: String
let color: String
let total: String
}
Then you can create a dictionary or an array with it:
var dictionary: [String: Object] = [:]
var objects: [Object] = []
I need to get the inner object value in localStorage.i.e object inside the object.
var filter = {
filterWord: null,
userId: null
}
filter.filterWord = listCAO.sortName;
filter.userId = listCAO.currentUser;
listCAO.filterBreadcumText.push(filter);
localStorage.setItem('entityBreadCumText', listCAO.filterBreadcumText);
LocalStorage only holds String pairs: 'string1'='string2'
So when you do localStorage.getItem('string1') it returns 'string2'.
If you want to store a Javascript Object, you need to convert it into a string first. JSON works best for that.
var myObj = [{'name': 'Paul', 'age': 22}, {'name': 'Steve', 'age': 68}];
myStr = JSON.stringify(myObj);
localStorage.setItem('myData', myStr);
Same when you read the data from localStorage
var myStr = localStorage.getItem('myData');
var myObj = JSON.parse(myStr);
var myName = myObj[0].name;
Or in one step
var myName = JSON.parse(localStorage.getItem('myData'))[0].name;
This may be another solution.
You can use it this way.
let obj = JSON.parse(localStorage.getItem('your_settings_name'));
let lobj: YourObject = <YourObject>obj;
If the data is stored as nested objects instead of an array as c14l 's answer, the syntax changes a little bit.
Let's store nested object first:
var myNestedObject = {"token": "Bearer", "profile": {"name":"Mustafa","expires_at":1678013824}};
myNestedStr = JSON.stringify(myNestedObject);
localStorage.setItem('myNestedData', myNestedStr);
Now let's see how to get the "name" from the nested object:
var nestedStr = localStorage.getItem('myNestedData');
var nestedObj = JSON.parse(nestedStr);
var nestedProfile = nestedObj.profile;
var nestedName = nestedProfile.name;
Or we can get "name" with a single line also:
var nestedNameWithOneLine = JSON.parse(localStorage.getItem('myNestedData')).profile.name;
Hi I have got a data in LocalStorage as JSON string:
[
{"Date":"28/04/2016","Time":"08:00","Title":"Title 1"},
{"Date":"28/04/2016","Time":"08:30","Title":"Title 2"}
]
And my module.factory looks like:
module.factory('$schedule', function() {
var schedule = {};
var result = JSON.parse(localStorage.getItem('myAgenda'));
schedule.items = [{
title: result.Title,
date: result.Date,
time: result.Time
}];
return schedule;
});
When I am trying to get data it returns undefined. When I try to get a specific object like:
console.log(result[0].Title);
It works fine and shows only the first element. I guess I missing each definition but don't know how to do it. Please help me to get all results in my schedule.items.
And I am passing the result as items into:
module.controller('ScheduleController', function($scope, $schedule) {
$scope.items = $schedule.items;
});
Many thanks.
You are trying to access fields in an array without mentioning wich array element you want to access. If you want to enumerate all agenda entries and add them to your array, it should look something like this:
module.factory('$schedule', function () {
var schedule = [];
var result = JSON.parse(localStorage.getItem('myAgenda'));
result.forEach(function (date) {
schedule.push({
title: date.Title,
date: date.Date,
time: date.Time
})
})
return schedule;
});
You should use .map over array, also add missing } in your last element of array.
var schedule = [];
//assuming result returns an array.
schedule = result.map(function(value){
return {
title: value.Title,
date: value.Date,
time: value.Time
};
})
Not familiar with module.factory, but it looks like result is an array of objects and you're accessing it like a single object when creating schedule.items.
You might have to iterate over the array and create an item per object in result.
I am having this format in my script
//declaration of JSON object
items= {};
items.values= [];
I need a structure like this, which is inserted automatically when the script is executed:
items :
{
key :['one', 'two', 'three', 'four'],
values: [1, 2, 3, 4]
}
Since the item.values[0] is undefined, it throws me a undefined error. Can anyone please tell me how to initialize the JSON object, such that it wont throw undefined error
I would like to insert like this:
var i=0;
item.key[i]= 'one';
item.values[i]= 1;
I am not sure whether this is the best practice, if anyone knows better way please post it!
Thanks in advance
You have the right idea. It looks like your property for adding keys isn't there though. Let's declare two properties, keys and values.
items= {};
items.keys = [];
items.values= [];
Our JavaScript object now looks like this
{ "keys": [], "values": [] }
var words = ['one', 'two', 'three', 'four'];
var numbers = [1,2,3,4];
You now want to iterate using a forloop. In JavaScript, arrays are 0-indexed, meaning the first element has an index of 0. That's why we initialize the i variable with a value of 0. After every iteration, we increment this variable and then check if it's less than the length of the array.
function populateObject() {
for (var i = 0; i < words.length; i++) {
items.keys.push(words[i]);
items.values.push(numbers[i]);
}
}
And then call your function
populateObject();
Here is the output
{"keys": ["one", "two", "three", "four"], "values": [1, 2, 3, 4]}
I have two json object with similar key question.
var data = {"question":[{
QuestionID : counter1,
QuestionText: question1,
Choices:[{ChoiceID:100,Choice:"Yes",NextQuestionID:counter},
{ChoiceID:101,Choice:"No",NextQuestionID:counter}],
AnswerType: answer_type
}]};
var data1 = {"question":[{
QuestionID : counter2,
QuestionText: question2,
Choices:[{ChoiceID:103,Choice:"Yes",NextQuestionID:counter},
{ChoiceID:105,Choice:"No",NextQuestionID:counter}],
AnswerType: answer_type
}]};
I want to concate them into one json object with key 'question' and value will be array like below
var final = {"question":[
{
QuestionID : counter1,
QuestionText: question1,
Choices:[{ChoiceID:100,Choice:"Yes",NextQuestionID:counter},
{ChoiceID:101,Choice:"No",NextQuestionID:counter}],
AnswerType: answer_type
},
{
QuestionID : counter2,
QuestionText: question2,
Choices:[{ChoiceID:103,Choice:"Yes",NextQuestionID:counter},
{ChoiceID:105,Choice:"No",NextQuestionID:counter}],
AnswerType: answer_type
}
]};
I tried many ways and below way close to my destination but it creats array of data and data1 object
var jsons = new Array();
jsons.push(data);
jsons.push(data1);
My problem will solve if i can concate question:Object and question:Array[2] where each index contains object. Final output will be question:Array[3]
Any help will be highly appreciated.
Thanks in advance.
I solved this problem by
var index = 0; // number of question
$.each(previousData.question,function(){
finalArray[index] = previousData.question[index]; //contain array
index++; //here index is number of question
});
finalArray[index] = data.question;
data = {'question': finalArray }; // convert array to object
You can merge through jquery
var final = $.merge(data, data1);
Well, your code is actually pushing two objects into a list so u get a list of objects. In your case, the first element is data and the second is data1. So you wouldnt actually get the required result.
Since you want an object try this
/* assuming data and data1 are created and both have the key question */
var final = {'question': [data.question, data1.question] };
// or using the concat feature
var final = data.question.concat(data1.question);