Accessing JavaScript object via key - javascript

I have a JavaScript object called data. I am using the following code to sort the keys in the object :
var index = [];
// build the index
for (var x in data) {
index.push(x);
}
// sort the index
index.sort(function (a, b) {
return a == b ? 0 : (a > b ? 1 : -1);
});
I then want to access the value for a particular index key in the following way :
for (var i=0; i<index.length; i++) {
var key = index[i];
document.getElementById(key).value = data.key;
}
However I am getting undefined for the data.key value. Can anyone suggest why ?

Change to
document.getElementById(key).value = data[key];
If the key you want to access is stored within a variable, you have to use the bracket notation. In your code, JavaScript will search for a key named "key" and thus fails.
Example:
var key = 'test';
console.log( data.key ); // yields content of data.key
console.log( data[key] ); // yields content of data.test

How about
Object.keys(data)[key] ?
Not sure it would work, without showing the structure of data.
edit: This way retrieves object key according to numerical index (0,1...,n), and not by name.

Related

How to add a value to an Object in javascript?

Let's take an example in javascript
var b = function(){
var key = {};
var result = [];
var a =
[{people: "people1"},
{people: "people2"},
{people: "people2"},
{people: "people3"}]
for(i=0;i<a.length;i++)
{
var val = a[i][people];
if(angular.isUndefined(key[val]))
{
Key[val] = "abc"; /////This line is foreign to my knowledge.
result.push(val);
}
}
return result;
}
Now in this Example i am creating an object Key and a array result.
The for loop will loop through the a variable and store the value of people property in the var val.
The angular.Isundefined function check whether the key[val] contains any duplicate data if not then it will add using the
Key[val] = "abc".
1) Now i have no idea how this line is creating the value and key pair in the key object.
2) Please tell me other ways to add value to the object.
O/P is as follows
key = Object {people1: abc, people2: abc, people3: abc}
hence it is adding value to key object without duplicating the value.
P.S. it is just an example not the real code.
From the link of Andreas in comments
I think this solves my problem.
the other way to add the key and value to the JSON object is like this.
obj = {};
obj[people1] = "data";
obj[people2] = "data";
obj[people3] = "data";
console.log(obj);
The key cannot be same but the value can be same.
So this is what my question was
Key[val] = "abc";
this line is getting the val variable dynamically and adding the val variable as the key and the value is abc.
Twist:
Do you think that
key.val = "abc";
work?
No:
This is what provided by the site
Any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number)
can only be accessed using the square bracket notation. This notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime).
in the following example i add count in my json my json come from ajax but i want to add count so add count below code that's work fine for me here .count is my custom value added by me, it is not part of my response
$scope.data = response.items;
for (var i = 0; i < response.items.length; i++) {
response.items[i].count = i;
}

Replacing underscore or lodash _.each with vanilla for loop

I'm wanting to replace the following code to no longer rely on the _.each() function of underscore.js or lodash.js:
function fset(data) {
_.each(dataDefault, function(item, key) {
var val = ( data[key] ? data[key] : dataDefault[key] );
$rootScope.meta[key] = val;
});
};
Ideally, I want to use a vanilla JavaScript for loop, but I don't understand how the _.each() function in underscore/lodash works to replace it...
Something like:
for(var i=0; i<data.length;i++) {
var val = ( data[key] ? data[key] : dataDefault[key] );
$rootScope.meta[key] = val;
}
But, I don't know how to get the key and item in this way...
dataDefault looks like:
var dataDefault = {
title: null,
description: null
};
An example of calling the function would be:
meta.fset({
title: 'Hello world',
description: 'DESC'
});
Try this:
Object.keys(dataDefault).forEach(function (key) {
var value = dataDefault[key]
// iteration code
})
With for..in you have to use hasOwnProperty to exclude inherit properties.
So, if I'm interpreting your logic correctly, what you're trying to do is loop through the keys in your defaults object, and if the object you're inspecting doesn't have that key, you want to add that key to the object and assign its value to the default value, is that correct? Any limitations on browser level?
The quickest way to do it if you know for sure what the default data object looks like would be to use a for..in loop:
var data = {}; // or wherever you get it from)
for (var key in defaultData){
data[key] = data[key] || defaultData[key];
}
That assumes that data.key is non-null and non-false. If false or null is a valid value (and your default is not null or false), then you'll want to make a bit more effort at ascertaining the existence of the key and type of the value. But based on your example, you're not worried about that.

How to find a property type from javascript object?

How can I find out which property of an object is an Array type?
Given the sample code below, I would expect to get the value OrderItemList.
function Order() {
this.Id = 0;
this.LocationID = 0;
this.OrderItemList = new Array();
}
var orderObject = new Order();
From what I understand, you have an Object in javascript and you want to know if it contains an Array or not. If that's what you want to achieve you can simply traverse through all the keys for that object and check if the value is an instanceOf array.
In Jquery, you could do something like this (updated Demo):
$.each( orderObject, function( key, value ) {
if(value instanceof Array){
console.log(key);
}
});
Javascript equivalent:
for (var key in orderObject) {
var val = orderObject[key];
if (val instanceof Array){
console.log(key);
}
}
I hope it gets you started in the right direction.
Edit - Like many have already pointed length attribute can not be used to uniquely distinguish an array from a string although you could do a typeof check to see if the value is a string.

Initialize a JavaScript object "tree" to any depth, nested objects

Essentially my I am trying to initialize a JavaScript object and have it contain empty objects with a single key. For example:
getOject('one.two.three')
Would result in the object:
{one:{two:{three:''}}}
As far as I can tell, you can't initialize with dynamic key names unless you use array notation
root[dynamicKey] = 'some variable';
so I need to loop through and based on the number of args initialize each one then assign it's value but the syntax doesn't seem to let me do this in any way that I know of.
So, if it were not a loop it would be like this:
jsonifiedForm[rootKey] = {};
jsonifiedForm[rootKey][childKeys[0]] = {};
jsonifiedForm[rootKey][childKeys[0]][childKeys[1]] = $input.val();
I can't think of a way to do this, I am not typically a JS guy so it might be something simple but I couldn't find anything on Google or Stack Overflow
Thank you in advance!
This function should be what you're looking for.
function getOject(str) {
// this turns the string into an array = 'one.two.three' becomes ['one', 'two', 'three']
var arr = str.split('.');
// this will be our final object
var obj = {};
// this is the current level of the object - in the first iteration we will add the "one" object here
var curobj = obj;
var i = 0;
// we loop until the next-to-last element because we want the last element ("three") to contain an empty string instead of an empty object
while (i < (arr.length-1)) {
// add a new level to the object and set the curobj to the new level
curobj[arr[i]] = {};
curobj = curobj[arr[i++]];
}
// finally, we append the empty string to the final object
curobj[arr[i]] = '';
return obj;
}
Because JavaScript references values in variables instead of copying them "into" variables, we can make our initial value, then make a reference to it which we'll move around as we delve down in:
var getOject = function (k, s) {
// initialize our value for return
var o = {},
// get a reference to that object
r = o,
i;
// we'll allow for a string or an array to be passed as keys,
//and an optional sepeartor which we'll default to `.` if not given
if (typeof k === 'string') {
k = k.split(s || '.');
}
// do we have an array now?
if (k && k.length) {
//iterate it
for (i = 0; i < k.length; i += 1) {
// set a property on the referenced object
r[k[i]] = {};
// point the reference to the new level
r = r[k[i]];
}
}
// send back the object
return o;
}
console.log(getOject('one.two.three'));
console.log(getOject('four|five|six', '|'));
r points to the same thing that o does, initially, and as we move the reference (r) deeper into o and write to it, we're building out o as we go.
The two console.log() calls at the end output the following:
Also notice I let you pass in an array to start with if you feel like it, and made the separator a parameter so that you're not stuck with .

Pass string to function to define property name

Good morning
I am wanting to pass a string as a functions parameter in java script but the string will represent the name of a property that i want the function to operate on. I have seen this done before but don't quite comprehend it.
the function below shows what i'm referring to with the "field" parameter. it's passed a value as a string but operates on the property who's name matched the value of the string.
What i want to do is cycle through the array of objects and return only the values stored in the property who's name matches the string passed. The idea is to have one function which can process any objects with properties that have been added to an array and return any property without having to write a loop function for each property.
Below is an example of this type of magic:
listName.sort(sort_by('stringPropertyName', false, function(a){return a.toUpperCase()}));
var sort_by = function(field, reverse, primer){ //http://stackoverflow.com/questions/979256/how-to-sort-an-array-of-javascript-objects
var key = function(x){return primer ? primer(x[field]) : x[field]};
return function (a,b){
var A = key(a), B = key(b);
return ((A < B) ? -1 :(A > B) ? +1 : 0) * [-1,1][+!!reverse];
}
}
If you want to "cycle through the array of objects and return only the values stored in the property who's name matches the string passed", you may do this :
function getValues(array, propname) {
var values = [];
for (var i=0; i<array.length; i++) {
if (typeof array[i][propname] !== 'undefined') {
values.push(array[i][propname])
}
}
return values;
}
The "trick" is to access the property using obj[propname] instead of obj.propname when propname is a variable containing the name of the property.
For example window.location can be accessed as window["location"]
DEMONSTRATION

Categories