This is probably really simple but I have a statement...
console.log($scope.data);
And in the console window I see...
[pension: "123", postcode: "GL"]
I have two questions...
What type of object is this?
How do I get access to the value (rather than the key) with a for
loop?
I tried...
for (item in $scope.data) {
console.log(item[1]);
}
But all I get is...
e
o
Not I cannot use the 'pension' or 'postcode' I need to be able to iterate the collection.
I was thinking I would need to use JSON.parse? But this seems like an overkill, because I originally instantiated $scope.data as an array. So why cant I access it like an array?
That's just how for..in loops work. The keys are assigned to item one by one, and then you use $scope.data[item] to get the value of that particular key.
Related
I have an array of objects that is fed by an external API e.g
[{prop: val1}, {prop: val2}, {prop: val3}....]
I have to feed this object(my code) to a third-party library which expects the name of the property on the object to be 'xyz' instead of 'prop'.
What is the most efficient way (memory wise and faster) basically avoiding both:
1. iterating over the array
2. adding 'xyz' property to all objects in the array
to achieve this?
I am thinking along the lines of adding a getter for xyz to all objects that return the 'prop' value, but that does not save the looping.
Adding the getting on the prototype level (Object.property) seems like a bad idea at this point.
Edit: I am not looking for different ways to loop through arrays in javascript like forEach or map. I have a very specific ask, and i am interested in exploring if it is at all possible to simply have a property proxy for 'xyz'.
Array map is used to cycle trough an array.
myArray.map(function(obj){
obj.xyz = 'yourvalue';
return obj;
}
You can use Array.map to create a new from the array you received by the API.
var newArray = oldArray.map(function(obj){
return {newKey : obj.prop};
});
In this example, newKey will be the key property you want, instead of 'prop', and it's assigned the old 'prop' value
I have an array of objects:
[object, object, object, object, object]
that i want to set a key to each using the object title:
{test:object, tester:object, foo:object, bar:object, test:object}
so i could say array.test instead of having to do array[0].title.
However the key can be generic, and when there are multiple objects with the same key it replaces the original.
Is what i want to do impossible without adding an index value to the key? In which case is the tidiest solution what i originally had array[0].title.
is there any way to set the same key to multiple objects without
replacing it other than appending an index value to to the key?
No. The object keys are unique, meaning a key can hold only one value. If you like to hold multiple value, then you assign array value to it. like { key : [value1, value2 ...]} but this is of no use for your problem. Also you are not sure what is the key value, and that is the whole objective of the object/map.
is the way im doing it the best way?
Yes. For the problem you mentioned using array data-structure/construct is good.
I have this code:
var dictionary=[
apple={name:"apple",pos:"noun",d:"",c:["fruit"]},
banana={name:"banana",pos:"noun",d:"",c:["fruit"]}
];
How could I access one of the objects in the array by using a string of its name. In the way that you could access an object as
object['propertyName']
is there a way to do something similar with an array? I want to access it in a way like
dictionary["apple"].pos
//Want to return "noun"
Is there a simple way to do something like that with an array, and if not is there an alternative method that I could use?
The way you're generating your dictionary s wrong; it's syntactically valid, but it's almost certainly not what you intended to do. It's not binding the key apple to that object. Rather, it's defining an implicit (global) variable named apple and assigning the object to that, as well as the first element of the array.
Try this:
var dictionary= {
apple: {name:"apple",pos:"noun",d:"",c:["fruit"]},
banana: {name:"banana",pos:"noun",d:"",c:["fruit"]}
};
console.log(dictionary["apple"].pos); // "noun"
// This also works:
console.log(dictionary.apple.pos); // "noun"
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>
Quick rookie question please.
Suppose I have a javsacript object like so:
var meh=[["cars",27], ["bikes",85], ["skates",4]];
To go through each data object here, I can do this:
$.each(meh, function(index,value){
console.log(value) //returns ["cars",27] etc..
});
And considering I know the place of, say, cars, I can do this to access it:
console.log(meh[0][0]) //shows "Cars"
and of course, if I want the value of cars, I need to do this:
console.log(meh[0][1]) //Shows 27
Now, I have the string - Keys, like cars, bikes or skates
But I cant figure out this: How do I access their respective values?
meh["cars"] is returning undefined, since, as I understand, it cant find a description outside each object.
I can do meh[0]["cars"] but it defeats the point as the position of cars might change.
How do I access a value of something with their key please?
thanks.
You should change that to objects
var meh={"cars" :27 , "bikes" :85, "skates" :4};
Now you can simply access it via keys
alert(meh['cars']); //27
If you have access to the code and can change the object, change it to something like this:
meh = {
'cars': 27,
'bikes': 85,
'skates': 4
};
and you can access them with keys like
meh["cars"] //will give you 27
If you cannot change the code, then the only way I see is using jQuery.each and comparing each key with your known key and assigning it to a temp variable.
Use an object instead:
var meh = {
"cars": 27,
"bikes": 85,
"skates": 4
};
You can iterate over it using $.each():
$.each(meh, function (key, value) {
// key == "cars" and value == 27, etc.
});
Accessing values works like this:
meh.cars
which is equivalent to this:
meh["cars"]
Obviously, the second notation can be used with variables.
You have your data structure in an array, so you are always going to have to access by the array syntax e.g. [0][1]. The arrays in JavaScript are not associative. You could write a helper function which iterates around the array looking for the key you specify and returning the value back. Or you could change your data structure to be Objects, which do support key lookup.
If you can't alter the object, you can create a map to make managing the indices simple. E.g.
map = {
'cars': 0,
'bikes': 1,
'skates': 2
};
Then, you can do:
alert(meh[map['cars']][1]);