Loop through different properties of a json using a sequence of numbers - javascript

I have a JSON with different properties called using a sequence of numbers (BOS1, BOS2, BOS3, BOS4, BOS5...). At a certain point of my code, I want to loop through them.
I know this doesn't work, but will give you an idea of what I'm trying to do:
for (var i = 0; i < data.length; i++) {
for (var j = 0; j < 14; j++) {
data[i].BOS+parseInt(j)
}
}
The code is more complex than that, as you can imagine, but the thing i'm trying to get data[i].BOS1, data[i].BOS2, data[i].BOS3, data[i].BOS4... And I'm not accomplishing to do it.
Thanks in advance!

You have to use the [] operator:
data[i]['BOS' + j]
For that to work (with the rest of your code), the object would have to look like this:
var data = [
{BOS0: "something", BOS1: "something", ... , BOS13: "something},
{BOS0: "something", BOS1: "something", ... , BOS13: "something},
...
];
Note that your loop starts at zero, not 1.

Related

How can I replace property names inside of an object? Javascript

My task is to create a function that swaps the names inside of the object with the names inside of an array.
Daniel's name should change to Felix and his age should remain the same. In the end, the object should look like this.
{Felix:18,Carlos:21,Sasha:22,John:20}
From This
{Daniel:18,Tyler:21,Michelle:22,Austin:20}
Heres what I have so far. I am new to programming so please try to take it easy on me.
function swapNames(oldNames,newNames){
for(var i in oldNames) {
for(var k = 0; k < newNames.length; k++) {
i = newNames[k];
}
}
console.log(i)
}
swapNames({Daniel:18,Tyler:21,Michelle:22,Austin:20},
["Felix","Carlos","Sasha","John"])
I thought this would loop through the object and the array and set the objects property name to the current string I am on. But when I console.log() the object is exactly the same.
Here is what you could do.
const swapNames = (inputObj, outputNames) => {
const output = {};
Object.keys(inputObj).forEach((key, index) => {
output[outputNames[index]] = inputObj[key];
});
return output;
}
console.log(swapNames({
Daniel: 18,
Tyler: 21,
Michelle: 22,
Austin: 20
}, ["Felix", "Carlos", "Sasha", "John"]));
I don't want give away the answer, but your problem is here
for(var i in oldNames) {
// when i = Daniel;
for(var k = 0; k < newNames.length; k++) {
i = newNames[k];
// you loop here keep change i from Daniel to "Felix","Carlos","Sasha","John",
// then you go back to above loop and repeat this, so all four old name got stuck with John
}
console.log(i)
}

When updating some of the elements in an object array in Javascript, which one is a more efficient way considering the array size?

Consider this very simple js code below:
for(var i = 0; i < rows.length; i++) {
if(rows[i].index !== i) {
rows[i].index = i;
}
}
Say, the length of the array is 8, and it will enter the if block 2 times. Is it better to do this way:
for(var i = 0; i < rows.length; i++) {
rows[i].index = i;
}
I want to know which one is less costly with large arrays and small arrays; the if block, or the value assign in every cycle of the loop?
it shouldn't really matter. I still tried it on jsPerf for the sake of curiousity and it seems that the second version is faster.

Javascript or Jquery - for each on this array

See a screenshot of my returned data i did a console.log on which i need to do a for each on.
i have been trying things like this to no avail...?
for (var point in arrayLatLngPoints)
{
addMarkers(point.timestamp, point.lat, point.lng, point.timestamp, strUserName, pathColour);
}
Don't use for..in to loop an array, use normal for loop instead.
for (var i = 0; i < arrayLatLngPoints.length; i++)
{
var point = arrayLatLngPoints[i];
addMarkers(point.timestamp, point.lat, point.lng, point.timestamp, strUserName, pathColour);
}

Merge loops with jQuery.extend: last value is always the same?

I have two arrays of "hashes". I need to merge them together so the end result is another array of hashes, except the number of entries is the product of the two arrays.
inhabitants = {}
idx = 0
for (i=0; i<persons.length; i++) {
person = persons[i];
for (j=0; j<houses.length; j++) {
house = houses[j];
console.log(house);
inhabitants[idx] = $.extend(person,house);
console.log(inhabitants[idx]);
idx++;
}
}
What I end up with is a silly number of entries that depends on the ordering of the parameters in the $.extend() line. And the "house" entry that is added is ALWAYS THE LAST ENTRY IN THE ARRAY.
Clearly this $.extend() from jQuery is not doing what I expect. Can anyone help?
$.extend(a, b) merges b into a, and returns a.
The return value you're using but it seems you were missing the fact that a is also being changed - you're currently assigning the same variable person to inhabitants[idx] each time.
I'm not really getting what you are trying to do, but anyway just a few hints. It's a good idea to place all the semicolons (here they're missing in the first and second line). Then I don't see why you are using an object instead of an array where you just have to push new items. Another thing is that in js it is faster to cache the lengths of the persons and houses collections. I will try to come up with code how I understood your task, maybe I'm getting it wrong:
var inhabitants = [],
idx = 0,
personCount = persons.length,
houseCount = houses.length,
person = {},
house = {},
i = 0,
j = 0;
for (i = 0; i < personCount; i++) {
person = persons[i];
for (j = 0; j < houseCount; j++) {
house = houses[j];
inhabitants.push($.extend({}, person, house);
}
}
So to me it seems like a database join between the two tables persons and houses. Is this what you meant?

Calling a javascript array without knowing naming conventions in advance

I am calling an ajax function that returns a dataset (response) with data column labels. One of the column labels changes depending on where the call was initiated from.
Normally the following code accesses the response variable if the column label is hard coded:
for (var i = 0; i < response.d.length; i++) {
data.setValue(i, 1, response.d[i].Emissions);
}
However, I need to be able to access the response variable using a separate string variable that is passed in since the label changes. Below is my feeble attempt at doing it, but it isn't working. What is the correct syntax for doing that?
var columnLabel = 'Emissions';
for (var i = 0; i < response.d.length; i++) {
data.setValue(i, 1, response.d[i].columnLabel);
}
You need to use the []-operator:
data.setValue(i, 1, response.d[i][columnLabel]);
obj.property is equivalent to obj['property'].
Try this:
for (var i = 0; i < response.d.length; i++) {
data.setValue(i, 1, response.d[i]['Emissions']);
}

Categories