1

like this object,

var myColumnDefs = [
 {key:"label", sortable:true, resizeable:true},
 {key:"notes", sortable:true,resizeable:true},......

I can call object as this method, which it works

...
 myColumnDefs.key
 ...

but how to call this object with Stringname like

function myObject (string) {
 return myColumnDefs.Stringname
}
alert(myObject('key'));
alert(myObject('sortable'));

thanks for Help

asked Jul 1, 2014 at 6:38
1
  • Is myColumnDefs an object or array of objects ? Commented Jul 1, 2014 at 6:55

3 Answers 3

2

You have to use myColumnDefs[Stringname] Here is the working fiddle And in your case you have to get the element by myColumnDefs[element_index][Stringname]

answered Jul 1, 2014 at 6:50
Sign up to request clarification or add additional context in comments.

Comments

1

First of all, I don't think this will work:

myColumnDefs.key;

You must reference one of the elements in the array:

myColumnsDefs[0].key;

With that in mind you can reference the property by its string name by doing this:

myColumnsDefs[0]['key'];

answered Jul 1, 2014 at 6:44

4 Comments

@cerbrus. That was a typo. Answering on a phone is hard. I'm trying to show how to index an object by its name. I think this is answering the question. Is it not?
So, you accidentally typed ( instead of [, right after [0]?.. That's better...
I'm not sure if this answers the question, since the question is vague, but at least the code works :) -1 removed.
+1 It does answer the question and also provides information about the indexing being incorrect so goes further.
0

There are 2 ways of doing this. One way is to change to array to an object with properties where the key name is a property. The other way is to search through the entire array and find the key with the correct name. I would suggest the first way, so the code would look like this:

var keyHolder = {};

for(var i = 0; i < myColumnDefs.length; i ++) {
 if(!keyHolder.hasOwnProperty(myColumnDefs[i].key)) {
 keyHolder[myColumnDefs[i].key = {
 sortable: myColumnDefs[i].sortable,
 resizeable: myColumnDefs[i].resizeable
 }
 }
}

Then you can do this:

keyHolder.label

Hope this helps.

answered Jul 1, 2014 at 6:44

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.