Javascript Double indexing Associative "array" Object [duplicate] - javascript

I am looking for a solution to create a single multidimensional associate array in javascript.
What I have: I have a mysql database I am accessing with php and have an array containing all fields (key,value pairs) in a single record. Their are upwards of 30 fields in each record so I am looking for a dynamic solution.
In the html coding, there is a form that is used to update a specific record in the table. I am using a function call on each input to fill a javascript array by key and value. The keys are identical to the keys in the php array.
In the function I am doing a json_encode call on the php array to pull in the "old" data to make it accessible to javascript.
What works: I am able to create a dynamic javascript associate array from the new data coming from the input function calls. I have tested this out using an alert after each call to the function.
What I need: A method to change the javascript array to a multidimensional array, pulling in the old value and adding it to the new array tied to the original key.
This works:
var changes={};
function change(key,value) {
changes[key[value]]=value;
for (key in changes) {
alert('key: '+key+'... value: '+changes[key]);
}
}
this is along the lines of what I am looking for:
var changes={};
function change(key,value) {
var oldInfo = eval(<? echo json_encode($oldInfo); ?>); //this from the php array
changes[key[newValue]]=value;
changes[key[oldValue]]=oldInfo[key];
for (key in changes) {
alert('key: '+key+'... value: '+changes[key[newValue]]);
}
}
Can someone point me in the right direction?
To clarify:
My php array $oldInfo holds the old information from the table, for example:
{fName=>"charles",lName=>"madison", etc.}
The javascript array hold new information:
{fName=>"Charlie",lName=>"Madison", etc.}
I would like a new multidimentional array (PHP) (or object in JavaScript) that would look something like this:
{fName=>{"charles","Charlie"}, lName=>{"madison","Madison"}, etc.}
lName and fName would be the key fields that are synonymous to both the PHP array and the JavaScript object.

It's really unclear what you want, but there are a couple of serious flaws with your logic:
var changes={}; ///this one way of declaring array in javascript
No, it isn't. That's an Object, which is very different from an array.
eval(<? echo json_encode($oldInfo); ?>);
You don't need eval here. The output of json_encode is JSON, which is a subset of JavaScript that can simply be executed.
changes[key[value]]=value;
This is totally wrong, and still a single-dimensional array. Assuming key is an array, all you're doing is inverting the keys/values into a new array. If key looks like this before...
'a' => 1
'b' => 2
'c' => 3
... then changes will look like this after:
1 => 'a'
2 => 'b'
3 => 'c'
For a multidimensional array, you need two keys. You'd write something like changes[key1][key2] = value.
Your variable naming is wrong. You should never see a line that reads like this: key[value]. That's backwards. The key goes between the [], the value goes on the other side of the =. It should read something like array[key] = value.
RE: Your clarification:
This doesn't work: {fName=>{"charles","Charlie"},...}. You're confusing arrays and objects; Arrays use square brackets and implicit numeric keys (["charles", "Charlie"] for example) while Objects can be treated like associative arrays with {key1: "value1", key2: "value2"} syntax.
You want an array, where each key is the name of a property and each value is an array containing the old and new values.
I think what you want is actually quite simple, assuming the "value" you're passing into the function is the new value.
var changes = {};
var oldInfo = <?= json_encode($oldInfo) ?>;
function change(key, value) {
changes[key] = [ oldInfo[key], value ]
}

This :
changes[key[newValue]]
Should be:
changes[key][newValue]

What I need: A method to change the javascript array to a multidimensional array, pulling in the old value and adding it to the new array tied to the original key.
Use aliases for the numeric indices to do this:
var foo = ["Joe","Blow"];
var bar = ["joe","blow"];
var names = {};
foo.fname = foo[0];
bar.fname = bar[0];
foo.lname = foo[1];
bar.lname = bar[1];
names.fname = [foo.fname,bar.fname];
names.lname = [foo.lname,bar.lname];

Related

React-Native doesn't extract strings from associative array in map

I cannot put strings from the associative array to another associative array. This is very weird phenomenon. This is the code and result
[Code]
p.phone_score_list.map(par => {
console.log(`par`, par);
console.log(typeof par.ipa);
phoneScoreList.push({
ipa: par.ipa,
// ipa: par.phone,
phone: par.phone,
pronuncedIpa: par.pronuncedIpa,
qualityScore: par.quality_score,
soundMostLike: par.sound_most_like,
});
});
console.log(`phoneScoreList`, phoneScoreList)
The result is below.
"ipa" and "pronuncedIpa" are "n" in the par parameter but after inputting the ipa into another associative array like the above code, it's gonna be undefined. Do you know the reason and how to handle it?
This is phone_score_list.
It's possible that you're assigning references to an object that has since been dropped from memory. I would try to create a new object like so
const newObject = { ...par };
phoneScoreList.push(newObject);

adding new key value in javascript array not affecting

I have array like this,
var serialize={};
Now, i have form and i am serializing that form and adding that to serialize in array like this,
var c=12;
ser[c]=$(elem).find('input[name!=material_id],select').serializeArray();
Which generates array like this,
ser[127][0][name] quantity_1_127
ser[127][0][value] 100
ser[127][1][name] single_1_127
ser[127][1][value] 11
ser[127][2][name] double_1_127
ser[127][2][value] 17.5
Now i just want to insert new key and value and i am doing it like this
ser[c]['test']='test';
But which is not affecting. What is the reason of this? Am i doing anything wrong here? Any alternate solution?
That's because ser[c] is an array and you are trying to use it as an object.
Add that test/test thing with:
ser[c].push({'test': 'test'});
Or, as your other values in the object are set:
ser[c].push({ 'name': 'test', 'value': 'test'});
This is not PHP where your indices in an associative array can be either strings or integers. This is javascript, where, if your indices in an object are integer, than that object is an array and if your indices are strings, your object is an ... well, object.
So, if you want to have something like ser[c]['mykey'] = value, you'll have to do something like:
ser[c] = { 'mykey': 'value'};
But this means that the ser[127][0] type of elements will be gone.

Every character in an array being recognized with ".hasOwnProperty(i)" in javascript as true with Google Apps Script

This is the array:
{"C8_235550":
{"listing":"aut,C8_235550_220144650654"},
"C8_231252":
{"listing":"aut,C8_231252_220144650654"}}
It was fetched with a GET request from a Firebase database using Google Apps Script.
var optList = {"method" : "get"};
var rsltList = UrlFetchApp.fetch("https://dbName.firebaseio.com/KeyName/.json", optList );
var varUrList = rsltList.getContentText();
Notice the .getContentText() method.
I'm assuming that the array is now just a string of characters? I don't know.
When I loop over the returned data, every single character is getting pushed, and the JavaScript code will not find key/value pairs.
This is the FOR LOOP:
dataObj = The Array Shown At Top of Post;
var val = dataObj;
var out = [];
var someObject = val[0];
for (var i in someObject) {
if (someObject.hasOwnProperty(i)) {
out.push(someObject[i]);
};
};
The output from the for loop looks like this:
{,",C,8,_,2,3,5,5,5,0,",:,{,",l,i,s,t,i,n,g,",:,",a,u,t,,,C,8,_,2,3,5,5,5,0,_,2,2,0,1,4,4,6,5,0,6,5,4,",},,,",C,8,_,2,3,1,2,5,2,",:,{,",l,i,s,t,i,n,g,",:,",a,u,t,,,C,8,_,2,3,1,2,5,2,_,2,2,0,1,4,4,6,5,0,6,5,4,",},}
I'm wondering if the array got converted to a string, and is no longer recognized as an array, but just a string of characters. But I don't know enough about this to know what is going on. How do I get the value out for the key named listing?
Is this now just a string rather than an array? Do I need to convert it back to something else? JSON? I've tried using different JavaScript array methods on the array, and nothing seems to return what it should if the data was an array.
here is a way to get the elements out of your json string
as stated in the other answers, you should make it an obect again and get its keys and values.
function demo(){
var string='{"C8_235550":{"listing":"aut,C8_235550_220144650654"},"C8_231252":{"listing":"aut,C8_231252_220144650654"}}';
var ob = JSON.parse(string);
for(var propertyName in ob) {
Logger.log('first level key = '+propertyName);
Logger.log('fisrt level values = '+JSON.stringify(ob[propertyName]));
for(var subPropertyName in ob[propertyName]){
Logger.log('second level values = '+ob[propertyName][subPropertyName]);
}
}
}
What you have is an object, not an array. What you need to do is, use the
Object.keys()
method and obtain a list of keys which is the field names in that object. Then you could use a simple for loop to iterate over the keys and do whatever you need to do.

How can I store values from one array to another array using 'for' loop

I am trying to create number of arrays like _temp0[],_temp1[],_temp2[] so on and I want to store values of data[] in it.
so value of data[0] goes in array_temp0[] after splitting,
data[1] goes in _temp1[] and so on
to elaborate more-
If value of data[0] is string a,b,c
then array _temp0[] should be
_temp0[0]=a
_temp0[1]=b
_temp0[2]=c
I wrote this function
for(var k=0;k<data.length-1;k++)
{
window['_temp' + k] = new Array();
alert("actual data -- >"+data[k]);
'_temp'+k= data[k].split(',');
alert("data after split -- >"_temp[k]);
}
but it is not working, how do I solve it?
You can do the same using javascript objects. Here is an example of how to do it.
Create an object of name '_temp':
var _temp = {};
When you iterate through 'data' variable then, you can dynamically add attributes to it,say _temp['data0'], _temp['data1'] etc, and every attribute will be an array. For that, you need to write something like:
for(var k=0;k<data.length-1;k++)
{
_temp['data'+k] = data[k].split(',');
}
This will not create the variables identical to what you want. However, this is similar to what you want.
used
window['_temp'+k]= data[k].split(',');
instead of
'_temp'+k= data[k].split(',');
and it worked, thanks to go-oleg

Create new multidimensional Associative array from 2 arrays

I am looking for a solution to create a single multidimensional associate array in javascript.
What I have: I have a mysql database I am accessing with php and have an array containing all fields (key,value pairs) in a single record. Their are upwards of 30 fields in each record so I am looking for a dynamic solution.
In the html coding, there is a form that is used to update a specific record in the table. I am using a function call on each input to fill a javascript array by key and value. The keys are identical to the keys in the php array.
In the function I am doing a json_encode call on the php array to pull in the "old" data to make it accessible to javascript.
What works: I am able to create a dynamic javascript associate array from the new data coming from the input function calls. I have tested this out using an alert after each call to the function.
What I need: A method to change the javascript array to a multidimensional array, pulling in the old value and adding it to the new array tied to the original key.
This works:
var changes={};
function change(key,value) {
changes[key[value]]=value;
for (key in changes) {
alert('key: '+key+'... value: '+changes[key]);
}
}
this is along the lines of what I am looking for:
var changes={};
function change(key,value) {
var oldInfo = eval(<? echo json_encode($oldInfo); ?>); //this from the php array
changes[key[newValue]]=value;
changes[key[oldValue]]=oldInfo[key];
for (key in changes) {
alert('key: '+key+'... value: '+changes[key[newValue]]);
}
}
Can someone point me in the right direction?
To clarify:
My php array $oldInfo holds the old information from the table, for example:
{fName=>"charles",lName=>"madison", etc.}
The javascript array hold new information:
{fName=>"Charlie",lName=>"Madison", etc.}
I would like a new multidimentional array (PHP) (or object in JavaScript) that would look something like this:
{fName=>{"charles","Charlie"}, lName=>{"madison","Madison"}, etc.}
lName and fName would be the key fields that are synonymous to both the PHP array and the JavaScript object.
It's really unclear what you want, but there are a couple of serious flaws with your logic:
var changes={}; ///this one way of declaring array in javascript
No, it isn't. That's an Object, which is very different from an array.
eval(<? echo json_encode($oldInfo); ?>);
You don't need eval here. The output of json_encode is JSON, which is a subset of JavaScript that can simply be executed.
changes[key[value]]=value;
This is totally wrong, and still a single-dimensional array. Assuming key is an array, all you're doing is inverting the keys/values into a new array. If key looks like this before...
'a' => 1
'b' => 2
'c' => 3
... then changes will look like this after:
1 => 'a'
2 => 'b'
3 => 'c'
For a multidimensional array, you need two keys. You'd write something like changes[key1][key2] = value.
Your variable naming is wrong. You should never see a line that reads like this: key[value]. That's backwards. The key goes between the [], the value goes on the other side of the =. It should read something like array[key] = value.
RE: Your clarification:
This doesn't work: {fName=>{"charles","Charlie"},...}. You're confusing arrays and objects; Arrays use square brackets and implicit numeric keys (["charles", "Charlie"] for example) while Objects can be treated like associative arrays with {key1: "value1", key2: "value2"} syntax.
You want an array, where each key is the name of a property and each value is an array containing the old and new values.
I think what you want is actually quite simple, assuming the "value" you're passing into the function is the new value.
var changes = {};
var oldInfo = <?= json_encode($oldInfo) ?>;
function change(key, value) {
changes[key] = [ oldInfo[key], value ]
}
This :
changes[key[newValue]]
Should be:
changes[key][newValue]
What I need: A method to change the javascript array to a multidimensional array, pulling in the old value and adding it to the new array tied to the original key.
Use aliases for the numeric indices to do this:
var foo = ["Joe","Blow"];
var bar = ["joe","blow"];
var names = {};
foo.fname = foo[0];
bar.fname = bar[0];
foo.lname = foo[1];
bar.lname = bar[1];
names.fname = [foo.fname,bar.fname];
names.lname = [foo.lname,bar.lname];

Categories

Resources