i want to store value like key and value pair in javascript
So far i am doing like this
var list_of_addressbook_entries = {};
list_of_addressbook_entries.guest_name = name ;
for(key in list_of_addressbook_entries)
{
alert("key " + key
+ " has value "
+ list_of_addressbook_entries[key]);
}
In the above code guest_name is a variable which value is coming from a onclick
so when i am doing the above it showing me the result like
key guest_name has value M
it is not printing the value of guest_name
i want the result like
key guest_name_variable value has key M
Please suggest me what to do here ?
If I've understood right, you need to use the bracket [] syntax, otherwise it is not interpreted as a variable:
list_of_addressbook_entries[guest_name] = name ;
Related
What I want is that my object listen to a string that I send to my function
for example :
const [object,setobject] = useState([]);
const HandleChange = (text,field) => {
if (Object.keys(object).length > 0){
var objects = values + ',' + '{"' +field +'":' + text + '}'
console.log(object[text])
setobject(objects);
}
else {
var objects = '{"' + field +'":' + '"'+ text + '"}'
setobject(objects);
console.log(object[field]);
}
}
from this object(which is a state) I want to get if there is any value equal to variable text inside my object, someone knows how can I find it ?
It seems there several typos in your code (object or objects, console.log(object[text]) or console.log(object[field]), ...).
What I understand is that you wish to access object[field], but object is a String and not an Object.
Following this premise I would suggest converting it to an actual Object first, using JSON.parse(). Then you could check if object[field] already exists.
I know there are a few other posts on this topic, but they don't seem to address my issue: link.
I want to be able to dynamically get the name of a specific property in an object so that I can use it to create a new property name inside another object. For example, I would get the property name startMin from foo (as in my code below) and then add text to the end of it (like startMin + Suffix) to create a new property name. How can I do this?
A related note: I've already figured out how to get the property value with foo[Object.keys(foo)[0]]. Though this works, I'm not sure why Object.keys gets the property value in this case since the examples I've found suggest Object.keys is supposed to get the property name not the property value. I'd love to know why?
I have included the pusdo code foo[Object.returnObjectName(foo)[0]] + 'Cal' where I want the name to be dynamically created. It doesn't work, of course.
var foo = {
startMin: 1000
};
var fooResults = {
// the property name here is psudo code
foo[Object.returnObjectName(foo)[0]] + 'Cal': foo[Object.keys(foo)[0]]
}
console.log('startMinCal: ' + fooResults.startMinCal) // This should log "1000" but won't until the object name inside `fooResults` is created correctly.
//
console.log(Object.keys(foo)); // I believe this gests the property name, but it exists inside an array, so won't work as a new property name
console.log(foo[Object.keys(foo)[0]]); // this gets the property value as expected.
UPDATED WORKING CODE:
var foo = {
startMin: 1000,
startMax: 3000
};
var fooResults = {
[Object.keys(foo)[0] + 'Cal']: foo[Object.keys(foo)[0]],
[Object.keys(foo)[1] + 'Cal']: foo[Object.keys(foo)[1]]
}
console.log('startMinCal: ' + fooResults.startMinCal)
console.log('startMaxCal: ' + fooResults.startMaxCal)
var foo = {
startMin: 1000
};
//Object.keys return all the keys in an object passed as parameter
//here your wanted key is at first position
var key = Object.keys(foo)[0];
//get the value
var value = foo[key]
//append whatever suffix you want
key += 'Cal';
var fooResults = {
//to use content of variable as key of object put variable in []
[key]: value
}
//another solution
//create emtyy object
var fooResults2 = {}
//use use variable name as index
fooResults2[key] = value
console.log('startMinCal: ' + fooResults.startMinCal) // This should log "1000" but won't until the object name inside `fooResults` is created correctly.
console.log('startMinCal: ' + fooResults2.startMinCal)
Thanks for the answers on the previous two questions. I have a new one, and this one is a collapsible panel in jQuery. The concept is, the first key of a JSON object will appear as a button, and the other keys will be treated as regular text like <p> and the like.
I have this function which tests for the first index of an object.
function isFirstIndex(obj){
var key;
for(key in obj){
if(obj[key]===0){
return true;
}
}
return false;
}
I have tried this one:
function generateTree(data, selId){
var cnt = "";
for (var i=0; i<5; i++){
var row = data[i];
$.each(row, function(key,value){
if (isFirstIndex(row)){
cnt += "<button>" + value + "</button><br/>";
} else{
cnt += "<strong>" + key + "</strong> :" + value + "<br/>";
}
});
cnt += "<br/>";
}
$(selId).html(cnt);
}
But eventually found out in debugging that the key in the isFirstIndex function is compared with a string.
Suppose I have a JSON :
{"userId" : 1, "name" : "cool name"}
I want to show the first key of any JSON set as a button, and the following properties will be ordinary text. Please allow me to post a pseudo-code like process.
Loop through all elements of data response
Loop through each key and value of each data element.
If the key is the first occurrence within the data set
display it as a button.
else
display it as ordinary text.
End Inner Loop
End outer loop
What UtsavShah means is that for (key in obj) may iterate keys in obj in any order, JS spec does not enforce any order.
In fact, JS spec does not enforce any order not only for iteration, but also for internal storage: each JS engine implementation (hence depending on browsers) may store your JSON keys in any order, so even though you write your "userId" first, it does not mean at all that the browser will keep it as the first key. For that, you have to use an Array, or use a convention with a specific key.
The way your code is written, it will look for a key named "0" in your object (row). BTW your i iterator is useless in isFirstIndex function.
What you may try to achieve is to test if the value assigned to "userId" key is equal to 0? In that case, you would simply test if (obj["userId"] === 0).
EDIT: (after you have explained that userId is the one to be a button)
If you just want the value in key "userId" to be displayed as a button, you would simply do:
function generateTree(data, selId){
var cnt = "";
for (var i=0; i<5; i++){
var row = data[i];
$.each(row, function (key,value) { // Note that $.each does not necessarily iterates in any specific order either.
if (key === "userId"){
cnt += "<button>" + value + "</button><br/>";
} else{
cnt += "<strong>" + key + "</strong> :" + value + "<br/>";
}
});
cnt += "<br/>";
}
$(selId).html(cnt);
}
EDIT2:
If you want an order, you need an array. If you want ordered keys, you could shape your data like so (of course this must be implemented in both server and client):
[
{"userId": 1},
{"name": "cool name"}
]
If you just need to know which particular key is specific and should be set as a button, make up a convention with your server and have your data specify which is the specific key, e.g.:
{
"userId": 1,
"name": "cool name",
"specificKeyToBeTransformedIntoAButton": "userId"
}
I have the following code:
//Populate inputData with the values of the input text boxes, in order
var inputData = {};
var x = document.getElementById("newInventoryForm");
//Added this following line in the edit
$('#additionalContent').append("My x.length property " + x.length + "<br/>");
for (var i = 0; i < x.length - 1; i++) {// -1 so we don't get the submit button
var addData = {
id : x[i].id,
value : x[i].value
};
inputData[i] = addData;
$('#additionalContent').append(inputData[i].id + " : " + inputData[i].value + "<br/>");
}
I'm attempting to pass the form data from a previously made form to another javascript function. Before I do that I have tried to make it all work in the same .js page, however when I try to output my inputData through a for loop, it shows up blank. I determined this is because inputData.length is undefined. I was under the impression that declaring it as inputData = {}; made it an array and thus had a default length value. How can I change this to have the correct length?
Edit
Several commenters have said that var x = document.getElementById("newInventoryForm"); should return null or a node, neither of which has a length property. Adding the line in the code above, has produced this output.
My x.length property 18
serialNumber : 456
someDatafield : someInput
You've declared it as an object.
Perhaps var inputData = []; will give you better results.
{} is an object, not an array.
You want [].
Also, getElementById() does not return an array; your entire code makes no sense.
How can I display object content without specifying the attributes ? (The object here is used as associative array)
alert(result[0].name);
alert(result[0].surname);
I actually would like to not have to write "name" and "surname", but display all the content (keys & values)
thanks
Try this.. (it uses for each loop):
var arr=[];
arr[0] = 'Test1';
arr['SomeKey'] = 'Test2';
for(var o in arr)
{
var val = arr[o];
alert("Key is: " + o);
alert("Value is: " + val);
for(var b in val)
{
alert("Inner Key is: " + b);
alert("Inner Value is: " + val[b]);
}
}
Maby this will help you:
for (var item in result[0]) {
var key=item;
var val=b[item];
alert('b['+key+']='+val);
}
Good luck!
Maybe as a clarification for the other answers:
result[0].name
is the same as
result[0]["name"]
However,
result[0][name]
would use whatever the current value of name is. E.g.
var name = "surname";
if (result[0][name] == result[0].surname) // this is true