How to find an object key using an variable? - javascript

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.

Related

How can I get the name of a property from inside an object to create a new property name?

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)

Inserting a string at a variable index

I have not been able to find a working example or a good explanation of how I can achieve the following: (I would appreciate if anyone can point me in the right direction.
I have a query string: **"/api/bla?sources=[1,2]&plans=[1,2]&codes=[1,2,3]"**
I will be updating the query string via either javascript or jquery when certain events occur on my page, doesnt matter which.
For example, there is a multi select dropdown on the page which houses [sources] and [plans] and [codes]... These dropdowns have IDs which i am to update my request url with upons selecting items in teh dropdowns.
When a source with ID "3" is selected from the dropdown (or checkbox, doesnt matter what page controls are being used) the query string parameter sources[1,2] will need a "3" appended. Likewise then if the item with an ID of "2" is unselected, it will likewise be removed from the query string leaving the new string as sources[1,3]
I am somewhat new to javascript/jquery and especially more advanced string manipulation. I have been attempting to recreate something to demonstrate this and have gotten to the following which is not fully working.
Basically my initial if statement works as intended, but the moment the else is hit (when another ID needs to be added to an existing model in the query string - like a second ID for [sources] or [codes]) it returns wonky output - seeng as I couldnt get the right formula to update everything correctly.
//TIMEMTABLE QUERY
function updateCalendar(filter_id, filter_element) {
//Run through the filter checks before making final call to query and update timetable?
//GET THE MODEL/OBJECT NAME
var queryName = filter_element.attr('data-owner');
//GET THE IDs //this is either an array of all selected IDs or a single id which is used in the else statement
var queryId = filter_element.attr('value');
var queryIds = $('#'+filter_id).val();
var modelCheckIndex = requestString.toLowerCase().indexOf(queryName.toLowerCase());
//build a request string
if (modelCheckIndex < 0) {
console.info('ADD MODEL TO QUERY STRING');
requestString = requestString + "&" + (queryName.toLowerCase() + "[" + queryIds + "]");
console.log(requestString);
}
else{
console.info('UPDATE MODEL ON QUERY STRING');
var position = requestString.toLowerCase().indexOf(queryName.toLowerCase());
//requestString = requestString.substr(modelCheckIndex -1, requestString.length -1) + "," + queryId + "]";
requestString = requestString.slice(modelCheckIndex.indexOf("]"), modelCheckIndex) + "," + queryId;
console.log(requestString);
}
//MAKE THE API CALL USING CREATED QUERY STRING
}
If anyone has any examples or fiddles lying around I would also appreciate it.
Fiddle I am trying to get to work
It looks like you are just having trouble parsing and updating a query string. In which case, I have a function I've been using for that (thank you Google)
function getUriParams(string) {
var params = {},
queryString = string.slice(string.lastIndexOf('?')).substring(1),
regex = /([^&=]+)=([^&]*)/g,
m;
while (m = regex.exec(queryString)) {
params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
return params;
}
The input is your requestString and the output is an object of key value pairs of the query string.
To make the object a string, jQuery makes it easy with $.param().
//get key value pairs
var obj = getUriParams(requestString);
//make query string
var str = $.param(obj);
I suggest to change the logic a bit. I would use some data storage for the wanted parameter and rebuild the request string every time when it's necessary, like the below example.
It is much more better, than rebuild the string each time when some value has changed.
var data = {
sources: [1, 2],
plans: [],
codes: [1, 3, 4]
};
function buildStr() {
function get(key) { return key + '=' + JSON.stringify(data[key]); }
return '/api/bla?' + ['sources', 'plans', 'codes'].map(get).join('&');
}
document.write('<pre>' + buildStr() + '</pre>');

js/jQuery - Converting array to string

The 2 drop downs I'm using to store into local storage are storing as an array.
How could I convert it where if any arrays are detected then convert it and store it as string instead?
Something like this?
if( Object.prototype.toString.call( value ) === '[object Array]' ) {
value.toString();
}
Please see my fiddle:http://jsfiddle.net/3u7Xj/137/
Showing being stored as:http://i.imgur.com/L78kGE7.jpg
local storage function:
save = function () {
$('input, select, textarea').each(function () {
var value = $(this).val();
var name = $(this).attr('name');
if($(this).hasClass('checkers')){
value = $(this).is(":checked")
if(value){
value='on';
}else{
value='off';
}
}
if(this.name.match(/^multiselect_/)){//removes buggy append
return false;
}
console.log('Saving');
console.log(name + ':' + value);
Survey[name] = value;
});
if (localStorage.getObj('Surveys') != null) {
Surveys = localStorage.getObj('Surveys');
}
Surveys[$('#FirstName').val() + '.' + $('#LastName').val()] = Survey; //store in big list
localStorage.setObj('Surveys', Surveys);
}
The easiest way to convert an array to a string is array.join(). Called just like that you get a comma-delimited string that contains all of the elements in the array. If you provide a separator (such as array.join('|')) you get a string that is delimited with the separator you provided. Where this fits into your saving function is up to you.
I would recommend using jQuery.encodeJSON()
http://forum.jquery.com/topic/jquery-encodejson
This way you can store your object as a JSON string.
You can then get your object back using the jQuery.parseJSON() function.
https://api.jquery.com/jQuery.parseJSON/
If i understood it right, i guess this could work:
Use Array.isArray method and then use JSON.stringify to turn the array into a string.
for (var key in this) {
//console.log(key, this[key]); //log to console
if($.isArray(this[key])) {
this[key] = this[key].join(':'); //change array to string separated by :
}
}

Json string values in javascript

I have following JSON string in a global variable in Javascript
var domains = {
"DomID00001": {
"ID":"DomID00001",
"Name":"Testdomein1"
},
"DomID00002": {
"ID":"DomID00002",
"Name":"Testdomein2"
}
};
What is the best way to retrieve the values from this JSON string and be able to use them in Javascript individually?
If I just alert the domains var it says = [object Object]
Using alert() will not show you objects, this is one of the big advantages of the console. Check this fiddle and use the console (pressing F12 on your browser). Then you understand how to refer to what is inside that object.
var domains = {"DomID00001":{"ID":"DomID00001","Name":"Testdomein1"},"DomID00002":{"ID":"DomID00002","Name":"Testdomein2"}};
console.log(domains);
console.log(domains.DomID00001);
console.log(domains.DomID00001.ID);
Since the keys are variable, you should probably use a for..in loop:
for( domid in domains) if( domains.hasOwnProperty(domid)) {
console.log(domid,domains[domid].ID,domains[domid].Name);
}
Try this:
var domains = {"DomID00001":{"ID":"DomID00001","Name":"Testdomein1"},"DomID00002":{"ID":"DomID00002","Name":"Testdomein2"}};
var strName1 = domains.DomID00001.Name;
var ID1 = domains.DomID00001.ID;
alert('Name: ' + strName1 + ' - ID: ' + ID1);

Javascript storing value in key value form

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 ;

Categories

Resources