Looping through Json and appending to object - javascript

I have this JSON response from Google Maps, saved to a .json file. It's a search for schools nearby.
I only want to extract the name and the location of the schools, and save these to the elemSchoolsArr variable for use later.
I don't know why the code I have below doesn't loop through the json response, checking elemSchoolsObj only show one object, instead of 10, which I would want to push to the elemSchoolsArr later.
var elemSchoolsArr = [];
var elemSchoolsObj = {};
$.getJSON('elementary-schools.json', function(data){
for (var i = 0; i < 10; i++) {
elemSchoolsObj.title = data.results[i].name;
elemSchoolsObj.location = data.results[i].geometry.location;
}
});
elemSchoolsArr.push(elemSchoolsObj);

You just need to push the object in to the array inside of the loop, so that each object is pushed in, rather than just one. Obviously this code snippet won't actually run because we're not getting your JSON here.
var elemSchoolsArr = [];
$.getJSON('elementary-schools.json', function(data){
for (var i = 0; i < 10; i++) {
var elemSchoolsObj = {};
elemSchoolsObj.title = data.results[i].name;
elemSchoolsObj.location = data.results[i].geometry.location;
elemSchoolsArr.push(elemSchoolsObj);
}
});
Here's a functional example...
var array = ["a", "b", "c", "d", "e"];
var first_try = [];
var second_try = [];
for( var i = 0; i < array.length; i++ ){
// we define our object in the loop but don't add it to the array
var obj = {
item: array[i]
};
}
// we push one object in to the array
first_try.push( obj );
// we get one object in the array
console.log( first_try );
for( var i = 0; i < array.length; i++ ){
// we define our object in the loop
var obj = {
item: array[i]
};
// we push each object we define in the loop in to the array
second_try.push( obj );
}
// we get all the objects in the array
console.log( second_try );

Related

Checking to see if key-value has the same value

So I'm turning a .csv file into an array of key-value pairs, I'm trying to print each unique value and i'm trying to figure out how I can check to make sure the values aren't identical. So for example:
var data = $.csv.toObjects(csv);
will turn everything into
[
{heading1:"value1_1",heading2:"value2_1",heading3:"value3_1",heading4:"value4_1",heading5:"value5_1"}
{heading1:"value1_2",heading2:"value2_2",heading3:"value3_2",heading4:"value4_2",heading5:"value5_2" }
]
I want to check if heading1 has the same value in both instances and if it does to only print the first instance of that value.
Convert your data into key–value pairs, where keys are the values from "heading1" like so:
var data = [
{heading1:"value1_1",heading2:"value2_1",heading3:"value3_1",heading4:"value4_1",heading5:"value5_1"},
{heading1:"value1_2",heading2:"value2_2",heading3:"value3_2",heading4:"value4_2",heading5:"value5_2" },
];
var filtered = {};
for (var i = 0, max = data.length; i < max; i++) {
var record = data[i];
if (!filtered[record.heading1]) {
filtered[record.heading1] = {};
}
filtered[record.heading1] = record;
}
var keys = Object.keys(filtered);
for (var i = 0, max = keys.length; i < max; i++) {
console.log(filtered[keys[i]]); // do print
}

Dynamic Key Value Array with Multiple Values in Javascript

I have:
var data = [];
I want to dynamically create string array like this:
for(var i=0; i < files.length; i++){
data[i].part1 = "abc";
data[i].part2 = "def";
data[i].part3 = "ghi";
}
Is this possible? I tried it and it complained 'Cannot set property 'part1' of undefined'
Then I want to sort the data array by part1 values so:
data[0] = {3,a,b};
data[1] = {1,a,b};
data[2] = {5,a,b};
becomes:
data[0] = {1,a,b,c};
data[1] = {3,a,b,c};
data[2] = {5,a,b,c};
The reason I want to do this is because after the sort is done, i need to change the
data[i].part2
to something else after sorting!
You could do this:
for (var i = 0; i < files.length; i++) {
data[i] = {};
data[i].part1 = "abc";
data[i].part2 = "def";
data[i].part3 = "ghi";
}
to set data[i] to an empty object, then fill it piece by piece. Or
for (var i = 0; i < files.length; i++) {
data[i] = {
part1: "abc",
part2: "def",
part3: "ghi"
};
}
to set data[i] to the complete object all at once.
I don't understand the data[0] = {3,a,b}; part, though: {3,a,b} is a syntax error and it doesn't resemble your other code (which doesn't mention 3 or a or b).
But you can easily sort an array of objects by a particular property:
data.sort(function (a, b) {
return (a.part1 > b.part1) - (a.part1 < b.part1);
});
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort for details.

JavaScript for loop closure issue

I am adding all categories after ticking them to true if they exists in selected categories of result but it combines previous categories results with current one. I tried closure but it doesn't give me fresh object. Check out fiddle.
var allCatsResult = [{"id":1},{"id":2}, {"id":3}, ... ];
var catsArray = [1, 2] // Array of ids from allCatsResult
var result = [
{"id":1, selectedCategories:[{"id":1},{"id":2}]},
{"id":2, selectedCategories:[{"id":4},{"id":5}]},
...
];
for (var i = 0; i < results.length; i++) {
var tmp = allCatsResult; // tried to add function form here didn't work
for (var k = 0; k < results[i].selectedCategories.length; k++) {
var index = catsArray.indexOf(results[i].selectedCategories[k].category_id);
if(index !== -1) {
tmp[index].ticked = true;
}
}
results[i].categories = tmp;
}
Above code gives combined result for ticked = true for all categories in each result.
You need to copy/clone the array of objects, or you're manipulating the original. There are a few ways apparently. I chose the following:
var tmp = JSON.parse(JSON.stringify(allCatsResult));
This will create a new array of objects in tmp, and it will correctly only modify the clone.

javascript object reference by array

How can I refer to an object element dynamically during a loop by using an array, something like this:
var obj = {};
var lvl = ['x','y','z'];
var ol = [];
for (var l in lvl){
ol.push( lvl[l] )
obj[ol] = 'someval'
}
so where the reference may be obj[x][y][z] so each time the loop iterates, an additional key reference is appended, but I do not know how many levels there will be.
Not sure if I have explained that very well ?!
Based on how you answered my comment I believe this code will provide the nested object structure you are looking for.
var obj = {};
var lvl = ['x','y','z'];
var ol = {};
for (var i = 0; i < lvl.length; i++){
obj[i] = {};
ol = obj[key];
}
You mean you want someval to be the value of obj.x.y.z? You can always refer to the newly created levels using a variable:
var obj = {};
var levels = ['x','y','z'];
var pointer = obj;
for (var l=0; l<levels.length; l++) {
key = levels[l];
if (l < levels.length-1) { // if not last element
pointer[key] = {};
pointer = pointer[key];
}
else { // if last element
pointer[key] = 'someval';
}
}
console.log(obj); // should log {x:{y:{z:"someval"}}}

Javascript arrays storing values

There might be a very simple solution my problem but just not being able to find one so please help me to get to my solution in the simplest way...
The issue here is that I have data being displayed in a tabular form. Each row has 5 columns and in one of the columns it shows multiple values and so that's why I need to refer to a value by something like this row[1]['value1'], row[1]['value2'] & then row[2]['value1'], row[2]['value2'].
I declare the array
var parray = [[],[]];
I want to store the values in a loop something like this
for(counter = 0; counter < 10; counter ++){
parray[counter]['id'] += 1;
parray[counter]['isavailable'] += 0;
}
Later I want to loop through this and get the results:
for (var idx = 0; idx < parray.length; idx++) {
var pt = {};
pt.id = parray[schctr][idx].id;
pt.isavailable = parray[schctr][idx].isavailable;
}
Obviously iit's not working because Counter is a numeric key and 'id' is a string key ..my question how do I achieve this ??
Thanks for all the answers in advance.
JS has no concept of "associative arrays". You have arrays and objects (map). Arrays are objects though, and you can put keys, but it's not advisable.
You can start off with a blank array
var parray = [];
And "push" objects into it
for(counter = 0; counter < 10; counter++){
parray.push({
id : 1,
isAvailable : 0
});
}
Then you can read from them
for (var idx = 0; idx < parray.length; idx++) {
// Store the current item in a variable
var pt = parray[idx];
console.log(pt);
// read just the id
console.log(parray[idx].id);
}
Like I did here
What you want inside your array is just a plain object:
// just a regular array
var parray = [];
for(var counter = 0; counter < 10; counter++){
// create an object to store the values
var obj = {};
obj.id = counter;
obj.isavailable = 0;
// add the object to the array
parray.push(obj);
}
later:
for (var idx = 0; idx < parray.length; idx++) {
var pt = parray[idx];
// do something with pt
}

Categories

Resources