UPDATE:
I initially agreed that the answer provided in the "duplicate" question helped, but it didn't. This isn't a duplicate question because I am trying to convert the string into a column name to use with d as in using dynamic and multiple data. The answer provided still uses a string and references data statically as in Data[0]["myString"] but what I am looking for is d.MyColumnWhichUsedToBeAString
ORIGINAL:
I would like to take a string from an array and then use that value to find the corresponding csv data.
Is this possible? If so, how:
Example:
//Ultimately, I want to return d.one
var myArray = ["one", "two", "three"}
//Is there a a way to get d.one from the array. For example
d.myArray[0]
In Javascript you need to use the [] property accessor syntax for variable index names:
var theValue = d[myArray[0]]
Related
I am trying to isolate the first value from an array that is constructed like below using JS:
[john,mike,tom]
I have tried the slice method but it is not working and I am assuming it's the way the array is constructed where the strings aren't enclosed in quotes. What would be the best way to transform the array above to either a string as a whole or a more properly formatted array so I can pull out any value I want?
edit For additional context, the array I mentioned above is the way is being passed to me from the source. I am trying to figure out how I can work with it to be able to slice up the values.
Sorry for the layman presentation of my question but I am still quite the beginner in JS and would appreciate it if anyone could help me out. Thanks!
In javascript, strings are enclosed in quotes. e.g.
'john', "mike" ect. so in order to create an array/list you need to put these values with quotes inside array and then access using index e.g.
var array = ['john', 'mike', 'tom']
console.log(array[0]); // john
Why do you need the strings to not have quotes? Is there an specific reason?
In js you need to put quotes on strings. If you try for example declaring an array in the way you did above the following will happen:
let x = [janaina,joao,julia]
VM203:1 Uncaught ReferenceError: janaina is not defined
at :1:10
So, correct way to delcare your array:
let x = ['janaina','joao','julia']
Now slice will work:
x.slice(0,1);
The result will be:
['janaina']
You can use the array prototype .shift(), but it will mutate your original array.
const john = {x: 124};
const mike = {x: 333};
const tom = {y: 355};
const slicy = [john, mike, tom].shift();
console.log(slicy);
I have an intention to set a field value of an object like this
$scope[nameOfField]=value;
which works if nameOfField is just field name.
However, if I define in $scope object "subObject":
$scope.subObject={};
var nameOfField='subObject.someSubField';
$scope[nameOfField]=12345;
this does not work. Apparently I can not address directly sub-object fields like this. I however do need to use nameOfField approach with sub-object fields, and appreciate hints how to make it work. I can not predict if subObject will be featured in nameOfField - it can be both name field and subObject.someSubField.
EDIT: Difference with the question Accessing nested JavaScript objects with string key is that I not only need to access value of object but modify it.
Well your current code would result into
$scope['subObject.someSubField']=12345;
which would be a syntax error. Correct would be
$scope[nameOfField1][nameOfField2]=12345;
So you need a function to archieve this. Here an example (obviously this has to be extended to support more then just the 2 levels):
var scope = {};
function setValue(scopeString, val){
var match = /(\w+)\.(\w+)/.exec(scopeString);
if(!scope[match[1]]) //create if needed
scope[match[1]] = {};
scope[match[1]][match[2]] = val;
}
function getValue(scopeString){
var match = /(\w+)\.(\w+)/.exec(scopeString);
return scope[match[1]][match[2]];
}
setValue('lvl1.lvl2', 1);
console.log(getValue('lvl1.lvl2'));
I have declared an object like this
var me = {'alex','moore','baby','you'};
without the property names. I just want the elements to be set of strings. But i get error in both chrome dev-tools and firebug. i have googled but can't find any good answer.
What am i doing wrong?
thanks.
EDIT
Thanks for your answers. The reason am asking is that i am reading a book "Javascript: The Definitive Guide". On page 115 of the PDF file, it states that Javascript Objects ::
"They can also be used
(by ignoring the value part of the string-to-value mapping)
to represent sets of strings."
So i was trying to test it but getting errors. It seems the book is wrong that they can be used to represent sets of strings.
If you want an ordered list of values, then use an array ([]), not a plain object ({}).
var me = ['alex','moore','baby','you'];
Objects must have named properties.
var me = {
foo: 'alex',
bar: 'moore',
baz: 'baby',
etc: 'you'
};
Seems like what you are looking for is an array
var me = ['alex','moore','baby','you'];
Objects on the other hand need to have properties defined.
Square brackets
var me = ['alex','moore','baby','you'];
You should be using array not object.
var me = ['alex','moore','baby','you'];
I know this isn't the best way to do it, but I have no other choice :(
I have to access the items in JSONObject by their index. The standard way to access objects is to just wirte this[objectName] or this.objectName. I also found a method to get all the fields inside a json object:
(for (var key in p) {
if (p.hasOwnProperty(key)) {
alert(key + " -> " + p[key]);
}
}
(Soruce : Loop through Json object).
However there is no way of accessing the JSONfields directly by a index. The only way I see right now, is to create an array, with the function above, get the fieldname by index and then get the value by fieldname.
As far as I see it, the p (in our case the JSON file must be an iteratable array to, or else the foreach loop wouldn't work. How can I access this array directly? Or is it some kind of unsorted list?
A JSON Object is more like a key-value-map; so, yes, it is unsorted. The only way to get around is the index->property name map you've already mentioned:
var keysbyindex = Object.keys(object);
for (var i=0; i<keysbyindex.length; i++)
alert(object[keysbyindex[i]]);
But why would you need these indexes? A unsorted map also has no length property, as an Array had. Why don't you use the for-in-loop
var counter = 0; // if you need it
for (var key in object) {
alert(object[key])
counter++;
}
? If you have a parsed JSON object, i.e. a plain JS Object, you won't have to worry about enumerable prototype properties.
Based on Bergis anserwer this is my solution:
var keysbyindex = Object.keys(this);
alert(this[keysbyindex[index]]);
return this[keysbyindex[index] || ""];
However, I think (not tested) it's extremly bad regaring performace and shouldn't be used! But desperate times require desperate measures.....
I don't think you can actually achieve this without creating your own parsing of JSON. You're writing that you want to go trough a JSON-object, but what you're actually trying to do is go trough a plain old Javascript object. Json is simply a string-representation used to transfer/store said object, and in here lies the main problem: the parser that transforms the string into an actual object (ie. the browser in most cases) can chose to ignore the order it finds the properties if it want to. Also, different browsers might have different approaches to parsing JSON for all you know. If they simply use a hash-map for the object that it's simple to loop through it, but the order won't be dependent on the order of the keys in the file, but rather the keys themselves.
For example, if you have the json {"b":"b","a":"a"} and do the for in loop, under some implementations you might end up with a comming first, and in others you might end up with b.
var jsn = {keyName: 'key value result come here...'};
var arr = jsn ? $.map(jsn, function (el) { return el }) : [0];
console.log(arr[0])
$('.result').text(arr[0]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="result"></span>
I have a js 'associative' array, with
array['serial_number'] = 'value'
serial_number and value are strings.
e.g. array['20910930923'] = '20101102'
I sorted it by value, works fine.
Let's say I get back the object 'sorted';
Now I want to access the first KEY of the 'sorted' array.
How do I do it? I can't think I need an iteration with
for (var i in sorted)
and just stop after ther first one...
thanks
edit: just to clarify, I know that js does not support associative arrays (that's why I put it in high commas in the Title).
2021 Update
Since ES6, properties with string keys are enumerated in insertion order. Here's a nice summary. My original answer from 2010 was correct at the time and is preserved below:
Original answer
JavaScript object properties are specified to have no order, much though many people wish it were different. If you need ordering, abandon any attempt to use an object and use an Array instead, either to store name-value objects:
var nameValues = [
{name: '20910930923', value: '20101102'},
{name: 'foo', value: 'bar'}
];
... or as an ordered list of property names to use with your existing object:
var obj = {
'20910930923': '20101102',
'foo': 'bar'
};
var orderedPropertyNames = ['20910930923', 'foo'];
Try this:
// Some assoc list
var offers = {'x':{..some object...}, 'jjj':{...some other object ...}};
// First element (see attribution below)
return offers[Object.keys(offers)[0]];
// Last element (thanks to discussion on finding last element in associative array :)
return offers[Object.keys(offers)[Object.keys(offers).length - 1]];
Actually JavaScript doesn't support associative arrays, so you can't loop through it in an implied order (e.g. you can't access it via the indexer property array[0] won't access the first element in your object). The syntax is what makes it look like it does, but in reality it doesn't. So you have no "Order" to your objects.
http://www.hunlock.com/blogs/Mastering_Javascript_Arrays
Javascript does not have, and does not
support Associative Arrays. However…
All arrays in Javascript are objects
and Javascript's object syntax gives a
basic emulation of an associative
Array. For this reason the example
code above will actually work. Be
warned that this is not a real array
and it has real pitfals if you try to
use it. The 'person' element in the
example becomes part of the Array
object's properties and methods, just
like .length, .sort(), .splice(), and
all the other built-in properties and
methods.
Just thinking off the top of my head, but could you have another array with the key value pairs swapped?
So the answer would be arrayKeyValueReversed['20101102'] = '20910930923';
When you sort the array, use the first item (array[0]) as the key to get the value in the arrayKeyValueReversed.