I have a piece of code to create an object literal array. The array is created from 2 other string array, one will become the object literal colHeads and the other array will be the data dataArr.
colHeads = [name, state]
dataArr = [John A. Smith,Joan B. Jones]
var temp = [];
var tempObj = {};
for (var i=0; i<colHeads.length; ++i) { // columns
var dataArr = colDatas[i].split(",");
for (var j = 0; j < dataArr.length; j++) { // data
tempObj[colHeads[i]] = dataArr[j];
}
temp.push(tempObj);
}
The final array should look like this:
var data = [
{name: 'John A. Smith', state: 'CA'},
{name: 'Joan B. Jones', state: 'NY'}
];
Problem here is according to this line tempObj[colHeads[i]] = dataArr[0]; The object literal would be replaced with the last entry in both arrays which make the result look like this:
var data = [
{name: 'Joan B. Jones', state: 'NY'},
{name: 'Joan B. Jones', state: 'NY'}
];
I'm new to javascript so I don't know much the syntax
First off, your loop is accessing the same dataArr index, it should be using j
tempObj[colHeads[i]] = dataArr[j];
Second, you are not constructing new tempObjs for each loop, so each item index shares the same tempObj which will end up leaving you with a list of the same exact object.
So far your code should look something more like this:
var temp = [];
for (var i=0; i<colHeads.length; ++i) { // columns
var tempObj = {};
var dataArr = colDatas[i].split(",");
for (var j = 0; j < dataArr.length; j++) { // data
tempObj[colHeads[j]] = dataArr[j];
}
temp.push(tempObj);
}
Lastly, You are only creating one tempObj for each column, rather than each row as you should be doing.
var temp = [];
var rowCount = colDatas[0].split(',').length;
for (var i = 0; i < rowCount; ++i) { // rows first
var tempObj = {};
for (var j = 0; j < colHeads.length; ++j) { // now columns
tempObj[colheads[j]] = colDatas[j].split(',')[i];
}
temp.push(tempObj);
}
Now, due to the way your colDatas object is set up, it requires you to split them for every loop which can become pretty costly, I suggest you find another way to store that so it can be better optimized.
Create new object in cycle (prepare arrays before it), like this:
for (var i=0; i<colHeads.length; ++i) {
var tmpObj = {};
tmpObj.name = colHeads[i];
tmpObj.state = colDatas[i]
result.push(tmpObj);
}
Related
I have a loop
var names = ['apple', 'pear', 'something']
var age = ['12','344','132']
(i have 20 vars like this)
for (var i = 0; i < names.length; i++) {
Something(names[i]);
}
i get the type of something with an jquery var name = $('[name=id]').val();
is it possible to do an if else so if the var name is equal to any of the variables like here above then the names.length will change into that.
Example if the outcome of the var name = $('[name=id]').val(); is age then the loop will change into
for (var i = 0; i < age.length; i++) {
Something(age[i]);
}
Yes, if you store those variables into an object.
var container = {};
container.names = ['apple', 'pear', 'something'];
container.age = ['12','344','132'];
var name = $('[name=id]').val();
for (var i = 0; i < container[name].length; i++) {
Something(container[name][i]);
}
[edit]
You can also check that what's stored in name corresponds to a valid array inside your container by calling Array.isArray(container[name]).
You can achieve this in a quite different way.
Define all you variables in an object like below.
var data = {
names: ['apple', 'pear', 'something'],
age: ['12','344','132'],
//...
}
here you get the type
var name = $('[name=id]').val();
Now do the loop like below, which should be as expected,
for (var i = 0; i < data[name].length; i++) {
Something(data[name][i]);
}
What you are saying might be possible depending on the scope of your variables. For example, if they are set globally on window, then you could potentially use Something(window[name][i]);, however I wouldn't recommend doing this. Instead I would set up your code with an object instead of variables, like this:
var data = {
names: ['apple', 'pear', 'something'],
age: ['12', '344', '132']
};
Then you can simply do what you describe:
var name = $('[name=id]').val();
for (var i = 0; i < data[name].length; i++) {
Something(data[name][i]);
}
Another way you could do this is by creating a function and passing in the appropriate variable:
var names = ['apple', 'pear', 'something']
var age = ['12','344','132']
function processItems(items) {
for (var i = 0; i < items.length; i++) {
Something(items[i]);
}
}
switch ($('[name=id]').val()) {
case 'name':
processItems(name);
break;
case 'age':
processItems(age);
break;
}
I would like to iterate through the key of an unordered dictionary in Javascript. I don't even know if it does exist or not.
At the moment I am having the following code :
var l = [5,3,2];
var unorderedDict = {};
for (var i=0; i<l.length; i++) {
unorderedDict[l[i]] = 'foo';
}
My dictionary will then be like : {2:'foo', 3:'foo', 5:'foo'} or in my case, I would like to keep the ordering of the initial list (so : {5:'foo', 3:'foo', 2:'foo'})
How can I achieve this ?
You cannot maintain order in object. If you want to maintain order use array:
var l = [5, 3, 2];
var val = ['foo', 'bar', 'baz'];
var unorderedDict = [];
// ^^
for (var i = 0; i < l.length; i++) {
unorderedDict[l[i]] = val[i];
}
// Iterate over array:
for (var i = 0; i < unorderedDict.length; i++) {
if (unorderedDict[i]) {
console.log(unorderedDict[i]);
}
}
EDIT
If you want the order to be the same as shown in l:
// Iterate over array:
for (var i=0; i<l.length; i++) {
console.log(unorderedDict[l[i]]);
}
I need help regarding insertion of array elements as objects into another array in Javascript. I have the following code:
tableLength = 3;
nyCourt = [];
oldArr = [Buy, String, Question]
for (var t = 0; t < tableLength; t++) {
nyCourt.push({});
for (var i = 0; i < OldArr.length; i++) {
nyCourt.Title = OldArr[i] ;
}
};
The code isnt working, I want output in the following format
[{Title:Buy },
{Title: String},
{Title: Question}]
But the output I get is this:
[{Title:Question },
{Title: Question},
{Title: Question}]
This line:
nyCourt.Title = OldArr[i]
writes to the Title property on the nyCourt object (which is an array object), repeatedly in the loop. The last assignment wins.
But given what you've said you want your output to be, your code is over-complex. You only need one loop:
var nyCourt = [];
var oldArr = [Buy, String, Question];
for (var i = 0; i < oldArr.length; i++) {
nyCourt.push({Title: oldArr[i] });
}
Live Example (use Chrome or something else modern) | Source
Or as this is Node so we know we have map:
var oldArr = [Buy, String, Question];
var nyCourt = oldArr.map(function(entry) {
return {Title: entry};
});
Live Example | Source
//this give the output you want
tableLength = 3;
nyCourt = [];
oldArr = ['Buy', 'String', 'Question'];
for (var t = 0; t < oldArr.length; t++) {
nyCourt.push({Title: oldArr[t]});
};
console.log(nyCourt);
place that push function inside the loop also change the code like this
for (var t = 0; t < tableLength; t++) {
for (var i = 0; i < OldArr.length; i++) {
nyCourt.push({"Title": oldArr[t]});
}
};
I have a JSON associate array
[{"Test":"5:00pm"},{"Testing2":"4:30 pm"}]
and I want to make it so that it becomes an array where
{
theatre = Test
time = 5:00pm
},
{
theatre = Testing2
time = 4:30 pm
}
But I can't figure out how to take a key name and make it a value...
Any help? I was looking at Object.keys but I couldn't find a suitable solution.
You have an array with object values. You'd need to loop over them:
var oldArray = [{"Test":"5:00pm"},{"Testing2":"4:30 pm"}];
var newArray = [];
for (var i = 0; i < oldArray.length; i++) {
var keys = Object.keys(oldArray[i]);
newArray.push({
theatre: keys[0],
time: oldArray[i][keys[0]]
});
}
http://jsfiddle.net/FNAtw/
This will give you an array stored in newArray with two elements. The first element is an object with kvps theatre: 'Test' and time: '5:00pm'. The second element is an object with kvps theatre: 'Testing2' and time: '4:30pm'.
Try this workaround:
var json = '[{"Test":"5:00pm"},{"Testing2":"4:30 pm"}]';
var betterJson = json.replace('{"', '{"theatre":"').replace('":"','",time:"');
If the JSON is always as simple as above, then this should work. But it's brittle...
If you have a JS object, you could use Object.keys. That will work in the latest browsers.
You can also loop each item and just save the 1st item.
var result = [];
var str = [{"Test":"5:00pm"},{"Testing2":"4:30 pm"}];
for (var i = 0; i < str.length; i++) {
var obj = {};
foreach (var key in str[i]) {
obj.theatre = key;
obj.time = str[i][key];
}
result.push(obj);
}
May be a bit clunky, BUT should work cross-browser.
var js = [{"Test":"5:00pm"},{"Testing2":"4:30 pm"}]
var newJSON = []
for(var i = 0; i< js.length; i++) {
for( var key in js[i]) {
if(js[i].hasOwnProperty(key)) {
var tmpJS= {};
tmpJS['theater'] = key;
tmpJS['time'] = js[i][key];
newJSON.push(tmpJS);
}
}
}
I am trying to create an object iteratively with the following structure:
var series = {
data: [{
name: 'some text',
y: 0
},
{
name: 'some other text',
y: 1
}]
}
Below is my code so far:
var series = {
data: []
};
var datatemp = {
y: '',
name: ''
};
for (var i=0; i<10; i++) {
datatemp.y = i;
datatemp.name = "namelabel"+i;
series.data.push(datatemp);
}
But what I am getting is the final values of series.data[i].y and series.data[i].name in all elements of the array, rather than what I expect, which is different values as the counter i iterates. I would appreciate your guidance on what I am doing wrong. Thanks in advance!
To add to what Mimisbrunnr said, you could even do it this way:
for (var i=0; i<10; i++) {
series.data.push({y: i, name: "namelabel"+i});
}
There is no need for the intermediate variable.
You need to make a new datatemp for each iteration of the for loop otherwise you are just passing the same object into the array each time and modifying it's values.
for (var i=0; i<10; i++) {
var datatemp = {};
datatemp.y = i;
datatemp.name = "namelabel"+i;
series.data.push(datatemp);
}
var series = {
data: []
};
for (var i=0; i<10; i++) {
var datatemp={};
datatemp.y = i;
datatemp.name = "namelabel"+i;
series.data.push(datatemp);
}
for (var i=0; i<10; i++) {
console.log(series.data[i].y);
console.log(series.data[i].name);
}
http://jsfiddle.net/Vp8EV/
Objects are passed by reference in javascript, in your example you only have one object which is referenced by the name datatemp, every time you assign a new value to one of its members the old member gets overwritten, so you have to create a new object for each iteration of the loop.