I have an array as follows. How would I retrieve the value of a specific key and put that value in a variable?
var obj = {"one":"1","two":"3","three":"5","four":"1","five":"6"};
So for instance if I want to get the value of "three" how would I do it in javascript or jQuery?
To get value in an object's key using a variable referencing that key with JavaScript, we can use square brackets. console. log(obj[name]); to get the name property of the obj object with obj[name] .
You need to make the object first, then use [] to set it. var key = "happyCount"; var obj = {}; obj[key] = someValueArray; myArray. push(obj);
Against what many think, JavaScript object keys cannot be Number, Boolean, Null, or Undefined type values. Object keys can only be strings, and even though a developer can use other data types to set an object key, JavaScript automatically converts keys to a string a value.
We must use a return keyword to return this object and return the obj created. We must create a variable myObj and then call the returnObj function. After we call this function, whatever the function will return (in this case, an object) will be stored inside the myObj variable.
Let's now try to return an object literal from a function instead of a primitive value. Let's assume we want the square function to return the square of the given number as a property of an object literal. This is how we'd traditionally define the function:
We are required to write a JavaScript function that takes in an object that maps literal values. The function should create an array of array, each subarray should contain exactly two elements. The first of which should be the key of corresponding object pair and second should be the value.
If no other logic is performed in an arrow function before the return statement, and it returns an object literal, it can be further simplified. To return an object literal from an arrow function, wrap it in parentheses: var myApp = ( () => ( { init: () => console.log ('MyApp init') }) ) ();
There's no return statement. What you need to do is force the parser to treat the object literal as an expression so that it's not treated as a block statement. The trick is to add parentheses around the entire body:
You can do this via dot or bracket notation, like this:
var myVariable = obj.three;
//or:
var myVariable = obj["three"];
In the second example "three"
could be a string in another variable, which is probably what you're after. Also, for clarity what you have is just an object, not an array :)
Here is a solution (by the way this is an object not an array):
var obj = {"one":"1","two":"3","three":"5","four":"1","five":"6"};
var myFunc = function(thisObj, property) {console.log(obj[property])};
myFunc(obj, "two");
//Output will be 3
You can also do this more easily using the _.pluck
function from the Underscore JS library.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With