Store function result to variable - javascript

How can I store the result of a function to a variable?
In navigating an object that contains an array, I am looking for one value, value1, once that is found I want to get the value of one of its properties, property1.
The code I am using below is an example and is incorrect.
function loadSets(id){
clworks.containers.find(function(i){
return i.get('property1')===id;
});
}
My intent is to navigate the object below:
clworks.containers
containers[0].property0.id
containers[1].property1.id
I am trying to determine how to find which item in the array has a property value equal to the id used in the function and then store it as a variable.

Simply:
var myVar = loadSets(id);
EDIT
Ok, as much as I understand your question now, your situation is the following:
You have an array containing objects called containers;
You want to iterate through this array, looking for the property id of the property property1 which equals the one specified in the function called loadSets(id);
Once found, store the object with the requested id in a variable.
Am I right?
If so, this should solve your problem:
// This function iterates through your array and returns the object
// with the property id of property1 matching the argument id
function loadSets( id ) {
for(i=0; i < containers.length; i++) {
if( containers[i].property1.id === id )
return containers[i];
}
return false;
}
After this you just need to do what I said in the first answer to your question, triggering it however you want. I put up a quick JSBin for you. Try to put 10, or 20, in the input field and then hitting the find button; it will return the object you are looking for. Try putting any other number, it will return a Not found.

Currently your function, loadSets, isn't actually returning anything and so you cannot store a result from it.
Try:
function loadSets(id){
return Base.containers.find(function(i){
return i.get('entityid')===id;
});
}
And to get a result into a variable:
var result = loadSets(id);

Related

Javascript JSON.stringify replacer return value problem?

I tried to write some javascript code that multiplies with number salaries of each person, and makes them into string with JSON.stringify.
For example, in salaries, the name and the original salary are in here like this:
let salaries = {
james:100000,
john:200000,
jane:300000
};
and I want to express like this: {james:110000,john:220000,jane:330000}
So, I wrote the code like...
let payjson = JSON.stringify(pays, function replacer(key, value){
return value*1.1;
}); // 1st try
and got an error, the values are changed like [object Object], NaN.
However, this code just worked for me
let payjson = JSON.stringify(pays, function replacer(key, value){
return Number.isInteger(value)? Math.floor(value*1.1): value;
}); // 2nd try
I wonder why the first one didn't work the way I wanted and the second just worked the way I wanted to.
As the stringify() function documentation clearly explain, the replacer function is initially passed the object, and then each of the properties. So, you are seeing this behavior. The first time when the value comes in as object type, and the multiplication is attempted, it crashes and does not subsequently pass the properties, so the overall return of the stringify() is null. In your 2nd try code, you are checking the value and only if it is of numeric type, you are doing the math and returning a calculated value, which is used by stringify() to append to the output string.
See the documentation, and mainly this paragraph :
Initially, the replacer function is called with an empty string as key representing the object being stringified. It is then called for each property on the object or array being stringified.
It looks like you want to create a copy of the original object with 10% higher salaries:
const salaries = {
james:100000,
john:200000,
jane:300000
};
const res=Object.fromEntries(Object.entries(salaries).map(([k,v])=>[k,1.1*v]));
console.log(res);
// this can be strigified too:
console.log(JSON.stringify(res));
// and the input object is unchanged:
console.log(salaries);
When the replacer function is first called, key is assigned an empty string. However, the function is still expected to return value, otherwise it terminates.
let salaries = {
james:100000,
john:200000,
jane:300000
};
document.write(JSON.stringify(salaries,(k,v)=>{return k==''?v:Math.floor(v*1.1);}));

access objects from json

I have an ajax call that receives a json encoded object on return.
success: function (response) {
jsonArrayResponse = jQuery.parseJSON(response["data"]);
autoSearchValue = jsonArrayResponse['autoresult'];
I want to be able to access the different parts of the decode. This is some sample return
{"success":true,"message":null,"messages":null,"data":"{\"errorText\":\"\",\"autoresult\":[{\"firstname\":\"Annon\",\"lastname\":\"Brooks\",\"date_of_birth\":\"1975-12-23 00:00:00\",\"id\":\"1\"},{\"firstname\":\"Josh\",\"lastname\":\"Ferns\",\"date_of_birth\":\"2000-09-02 00:00:00\",\"id\":\"2\"},
{\"firstname\":\"Alan\",\"lastname\":\"Templeton\",\"date_of_birth\":\"1975-08-02 00:00:00\",\"id\":\"3\"}}]}
I've found that I can access the firstname by
autoSearchValue[0]['firstname'];
but I can't figure out how to loop through the other firstname values. I'm guessing it's straightforward once you know how.
Any help would be great thanks
autoSearchValue is an array. Just use an index in a loop:
for (let index = 0; index < autoSearchValue.length; index++) {
autoSearchValue[index]['firstname'];
}
Maybe try to loop throught the length of the json object? Each loop will increment the counter since you get the first name with autoSearchValue[0]['firstname'] then find the next one with autoSearchValue[1]['firstname'] until the length is reached.
You can access by iteratig over the object. As an option you can use map function to iterate over the array, the callback function will receive current value on the argument
which you can either modify or process
autoSearchValue.map((value) => {
console.log(value.firstname)
})

Assigning a value to a variable changes value of right hand side

I'm new to JavaScript and feel like I must be missing something fundamental here!
I'm creating a function which sorts a list of integers list and returns the minimum value listSort[0].
function sortNumber(a,b) {
return a - b;
}
var min = function(list){
console.log(list[0]);
var listSort = list.sort(sortNumber);
console.log(list[0]);
console.log(listSort[0]);
return list[0];
}
Can anyone explain why the value of list[0] changes after list.sort(sortNumber) is assigned to listSort ?
Thanks!
The sort() function directly changes the array to which is applied. For example:
myArray.sort();
directly changes the content of myArray.
If you do not want to change the content of the original array you need to use a cloning function:
function mySortingFunction(list){
var newList = myCloningFunction(list);
newList.sort();
return newList;
}
There are several ways to clone an array:
Javascript fastest way to duplicate an Array - slice vs for loop
If you use AngularJS you can simply write:
var newList = angular.copy(list);
To get the minimum value of an Array, better use Math.min
var list = [4,2,4,2,6,5,2,4,3,5,2];
var min = Math.min.apply(null, list);
If i'm right, it's because when you use your assignment, you are executing list.sort(sortNumber) and so list change as per the assignment function.
Sooo... read like this :
- list.sort(sortNumber) => List change
- list is assigned to listSort
Despite this fact, I think you're going to far to find the min value. :P

Get ID by key in localStorage

In JS localStorage I can use
localStorage.getItem(key);
to get the value of the entry corresponding to the key in the key variable.
How can I get the entry's ID (instead of value) using the key?
Edit: sorry I must have confused people. What I mean by "key" is the numerical key - which is 0, 1, 2, 3 etc depending on how many items have been saved. Then I want to find out the ID it was stored as, eg foo in the below example, from the numerical key.
localStorage.setItem('foo', 'bar');
LocalStorage is implemented as a key-value pair ( see for instance: https://developers.google.com/web-toolkit/doc/latest/DevGuideHtml5Storage ) - so you don't have an id like an unique auto-incremented id in a database table.
However, you can access the elements using an index - to get the index of a key in localStorage, the only way I can find is to loop through each key until you find the one you are searching for, like this:
var findIndexOfKey = function(searchKey) {
for (var i = 0; i < localStorage.length; i++){
var key = localStorage.key(i);
if(key === searchKey)
return i;
}
return -1;
}
And then, to retrieve the key using the index, you can do:
localStorage.key(myIndex);
And to retrieve the value, you can do this:
localStorage.getItem(localStorage.key(myIndex));
... or this ( which would be equivalent to localStorage.getItem("myKey")):
localStorage.getItem(localStorage.key(findIndexOfKey("myKey")));
when setting the item you should give it's ID as a value and than when you call getItem(key) it should give it's ID as a return ex:
localStorage.setItem('foo', 'bar');
localStorage.getItem('foo'); // it should return the bar
take a look for this examples it may help : http://mathiasbynens.be/notes/localstorage-pattern
The answer:
localStorage.key(key);
Sorry, I realise I've got confused between what's actually called the key, which I called the ID, and it's numerical ID which I called the key...
I don't think it is possible. Can't you just make localStorage.setItem(yourkey,value)? I mean
localStorage.setItem(0,value)
localStorage.setItem(1,value)
This may be useful in loops for example.

Create object property names using loop and input textboxes

I am refactoring some code where I grab the values inputted into textboxes and use said values for calculations. The problem is rather than using document.getElementByID multiple times I want to loop through each textbox on the page and assigning each value to this object which I will pass to my calculation functions. I would also like to set the property names of this object by looking at the input textbox IDs and using the ID strings for the object property names.
See code below:
$(document).ready(function() {
var calcObj = new Object();
$("input[id^='txt']").each(function(i, val) {
calcObj[i] = this.value;
});
$.each(calcObj, function(i, val) {
// alert(val);
});
});
As you can see when document is ready, object is created. There is a jquery .each loop to go through every input with id that contains txt. I am assigning this.value to object where index is i.
So I want to some how name the properties of this object and assign value so I can reference object property name elsewhere in the code where I pass this object to another function.
Thanks.
As far as I understand, you want:
calcObj[this.id] = this.value;
I don't exactly get what you're asking for, because it seems like you're already doing what I think you're asking.
Right now, you're doing:
calcObj[i] = this.value;
That's no different from assigning it like:
calcObj['foo'] = this.value;
// and later we can access that via
alert( calcObj.foo ); // or calcObj['foo']
You can be dynamic with that as well, like:
calcObj[this.id] = this.value;

Categories

Resources