JSON Assoc Array to Variables? - javascript

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);
}
}
}

Related

adding an array into an array at a particular position (based on key value) in javascript

I searched a lot, but I could not get a satisfactory answer on the net. In javascript, how do I add an array into another multidimensional array at a particular position based on a key value?
finalArray = []; //final result to be stored here
for(var i=0; i<5; ++i)
{
var temp = [];
for(var j in $scope.team[i])
{
// counter = some value calculated here
temp[j] = $scope.team[i][j][counter];
}
finalArray[group[i]] = temp; // This gives an error
}
basically, I have
group = [ 'alpha' ,'beta', 'gamma' ]; //this array generated dynamically
my finalArray should be like,
finalArray['alpha'] = [ some records ];
finalArray['beta'] = [ some records ];
....
As far as I know, the way to add array into another array is to use .push() method, but that creates indices as 0, 1, 2... which is not desired. Please help me out
You have to use Object instead of Array. Make the following changes in the code
finalArray = {}; //final result to be stored here
for(var i=0; i<5; ++i)
{
var temp = {};
for(var j in $scope.team[i])
{
// counter = some value calculated here
temp[j] = $scope.team[i][j][counter];
}
finalArray[group[i]] = temp;
}
console.log(finalArray); //to see the object key value structure
now you can reference the values in finalArray with group[i] name. Hope this helps
You have to define your finalArray variable as Object instead of and Array:
var finalArray = {}; //or better in your case finalMap
var group = [ 'alpha' ,'beta', 'gamma' ];
var finalArray = {}; //declare it object as you dont want 0,1 indexes
for (var index in group){
finalArray[group[index]] = "some records/arry of records"
}
console.log(finalArray);
DEMO

Add different value to the same object literal javascript

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);
}

Form an array from the for-loop

I have a for loop in which I am getting all the values one by one but I need to form those values into one array.
Can any one let me know how to get form all the values into one array.
for (var i = 0; i < marray.length; i++) {
mId = marray[i].id;
var yourArray = [];
yourArray.push(marray);
console.log(marray);
}
Output getting from the above code is : ["0123"] and ["3456"]
But the expected output is ["0123","3456"]
You are creating a new yourArray for each loop iteration. Instead of doing that, create it just once before starting the loop:
var yourArray = [];
for (var i = 0; i < marray.length; i++) {
mId = marray[i].id;
yourArray.push(mId);
}
Note that I have changed the code to read yourArray.push(mId) because from the question it seems that's what you want -- not yourArray.push(marray).
A more compact way of doing the same is to use the array map function like this:
var yourArray = marray.map(function(row) { return row.id; });
This last version won't work out of the box in IE 8, so if you care about that you need to take appropriate measures.
decalare variable in outside for loop..
var yourArray = [];
for (var i = 0; i < marray.length; i++) {
mId = marray[i].id;
yourArray.push(mid);
}
console.log(yourArray);
Initialise yourArray before the loop
Try this
var yourArray = [];
for (var i = 0; i < marray.length; i++) {
mId = marray[i].id;
yourArray.push(mId);
}
The var yourArray is initialized to null each time you enter the loop. Define it outside loop.

Loop through and compare javascript objects

I have two arrays which are created from the inputs of a user like so:
var impArray = [];
$('[id^=imp]').on('change', function(){
var value = $(this).val();
var name = ($(this).attr('name').replace('imp-',''))
impArray[name] = value;
console.log(impArray);
})
var assessArray= [];
$('[id^=assess]').on('change', function(){
var value = $(this).val();
var name = ($(this).attr('name').replace('assess-',''))
assessArray[name] = value;
console.log(assessArray);
})
These create arrays like
assessAray
1-1: 10
1-2: 15
1-3: 9
impArray
1-1: 6
1-2: 14
1-3: 2
I then need to do a simple calculation with the matching keys like:
$('#comp-1-1').val(impArray['1-1'] / assessArray['1-1'] * 100);
Obviously I can't do this with every single one, so,
Question: How can I loop through the arrays and compare them based on keys then do something with their values?
Technically, you are working with JavaScript objects, not arrays. Your variable declarations should actually be:
var impArray = {};
var assessArray = {};
Once you have the correct variable declarations, you can use jQuery.each to iterate through keys (not indexes):
$.each(impArray, function(key, value){
$('#comp-'+key).val(assessArray[key]/value*100);
});
Try using $.each(), like:
$.each(impArray, function(i, v){
$('#comp-'+i).val(v/assessArray[i]*100);
});
Does this help you?
$.each(impArray, function(index, value){
var result = assessArray[index] / value * 100;
$('#comp-1-'+index).val(result);
});
If both arrays will always be the same length and have the object property at the same index, this should work:
http://jsfiddle.net/9DBuD/
assessArray = [{'1-1':'10'},{'1-2':'15'},{'1-3':'9'}];
impArray = [{'1-1':'6'},{'1-2':'14'},{'1-3':'2'}];
for(var i=0;i<assessArray.length;i++){
for(var prop in assessArray[i]){
for(var property in impArray[i]){
if(prop == property){
$('#comp-'+prop).val(impArray[i][property]/assessArray[i][prop]*100)
}
}
}
}
Edit
This modified fiddle and code should produce the same results even if the array indexes and sizes do not match:
http://jsfiddle.net/9DBuD/1/
Array.prototype.indexOfProp = function (property) {
for (var i = 0, len = this.length; i < len; i++) {
if (this[i][property]!=undefined) return i;
}
return -1;
}
assessArray = [{'1-2':'15'},{'1-3':'9'},{'1-1':'10'},{'1-4':'10'}];
impArray = [{'1-1':'6'},{'1-3':'2'},{'1-2':'14'}];
for(var i=0;i<assessArray.length;i++){
for(var prop in assessArray[i]){
var index = impArray.indexOfProp(prop)
if(index!=-1){
$('#comp-'+prop).val(impArray[index][prop]/assessArray[i][prop]*100)
}
}
}

converting array of array into array of keyvalue pairs

I want to convert array of array into array of key-value pairs using javascript or jquery.
i have array of array like :
var arrOfarr = [[1,'One'],[2,'Two'],[3,'Three']];
how do i convert arrOfarr into the array of key-value pairs that looks like
[{id:1,text:'One'},{id:2,text:'Two'},{id:3,text:'Three'}]
var result = [];
for (var i = 0, iLength = arrOfarr.length; i < iLength; i++) {
result.push({ id: arrOfarr[i][0], text: arrOfarr[i][1] });
}
console.log(result);
you can use $.map()
arrOfarr = jQuery.map(arrOfarr, function(val){
return {id: val[0], text: val[1]}
})
Demo: Fiddle
var arrOfarr = [[1,'One'],[2,'Two'],[3,'Three']];
var hash = new Array(arrOfarr.length);
for (var x = 0; x < hash.length; x++) {
hash[x] = {id: arrOfarr[x][0], text: arrOfarr[x][1]};
}
This might help you with performance if you have a large array or a lot of arrays because it'll allocate the size of the array in advance.
var result = [];
for(var i = 0; i < arrOfarr.length; i++){
var ar = arrOfarr[i];
result.push({ id: ar[0], text: ar[1] });
}
You can;
var arr = [[1,'One'],[2,'Two'],[3,'Three']];
var o = []
for (var i = 0; i < arr.length; i++)
{
o.push({id: arr[i][0], text: arr[i][1]});
}
try this,
a=[[1,'one'],[2,'two'],[3,'three']];
$.each(a,function(id,value){
a[id]={id:value[0],text:value[1]};
});
now a will have three objects as you want.

Categories