Javascript arrays as objects [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Length of Javascript Object (ie. Associative Array)
Loop through JavaScript object
var location = {
"Steve": "New York",
"Abigayle": "Chicago"
}
for (var i = 0; i < location .length; i++)
{
console.log('works');
}
I'm trying to make an array, where each item has some name and value.
The code above doesn't work. Tryed to make an object, but it doesn't have a length property - no for loop.
location= {
"Steve": "New York",
"Abigayle": "Chicago"
};
Is it possible to use arrays in this context?

If you just want to work with what you have,
var location = {
"Steve" : "New York",
"Abigayle" : "Chicago"
}
for (var name in location) {
console.log( name, location[name] );
}
If you care about the length, use an Array of objects
var location = [
{ key : "Steve", value : "New York" },
{ key : "Abigayle", value : "Chicago" }
];
But there is no easy way to look it up, it would require a loop.

Just for reference, you can iterate over all the keys in an object:
location = {
"Steve": "New York",
"Abigayle": "Chicago"
};
for (var elem in location) {
console.log(elem);
}
Produces:
Steve
Abigayle
But I think that one of the other answers is probably the correct way to what you're looking for.

You can loop over object keys aswell. Only if you require indexed keys you should use an Array here.
var loc = {
"Steve": "New York",
"Abigayle": "Chicago"
};
Object.keys( loc ).forEach(function( name ) {
console.log('name: ', name, ' city: ', loc[ name ] );
});
By the way, location is a (pretty much) reserved variable name within the window object. You can't really overwrite that, so you should re-name that variable.
The above code uses Ecmascript 262 edition 5 code which works in all modern browsers. If you want to support legacy browsers you need to load any of the various ES5 shim libraries

var locations = [
["Steve","New York"]
,["Abigayle","Chicago"]
];
or
var locations = [
{Name:"Steve",Location:"New York"}
,{Name:"Abigayle",Location:"Chicago"}
];
you could output the data in the 1st option like this:
var delimiter = " ";
console.log("var locations = [");
for (var i=0; i<locations.length; i++)
{
var innerdelimiter = "";
var line = delimiter + "[";
for (var j=0; j<locations[i].length;j++)
{
line += innerdelimter + locations[i][j];
innerdelimiter = ",";
}
line += "]";
console.log(line);
delimiter = " ,";
}
console.log("];");
and data in the 2nd option like this:
var delimiter = " ";
console.log("var locations = [");
for (var key in locations)
{
console.log(delimiter + "{" + key + ":" + locations[key] + "}");
delimiter = " ,";
}
console.log("];");

Related

Iterating values using Object.Keys

I am trying to iterate through vales of properties of an object.
here is my code
var player =
{
name: 'kaka',
age: 33,
address: '22 green street',
sayHello: function () {
console.log('my name is ' + this.name + "my age is " + this.age);
}
}
var myProperties = Object.keys(player);
for (var i = 0; i < myProperties.length; i++) {
console.log(myProperties[i]);
}
But it only displays the properties and not values.
How can i go through values like 'kaka' for name..
Thanks.
You would need to use the keys as lookup in original object
for (var i = 0; i < myProperties.length; i++) {
if(typeof player[myProperties[i]] !== 'function'){
console.log(player[myProperties[i]]);
}
}
In the end I'm not sure you gain much creating and iterating the keys vs using a for in loop for this use case
Note that since Object.keys returns an Array, you can use an iterator like forEach for convenience:
Object.keys(player).forEach(function(key) {
console.log(key + ': ' + player[key]);
});

Convert an array of object to array of string?

I'm having an array of object like this-
var person = [
{name: 'saprsh', age: 22, address:'XYZ'},
{name: 'Ankur', age: 23},
{name: 'Richa', age:25, adddress:'ABX', email:'abc#xyz.co'}
];
now i want output like this
var string_person = [{sparsh22XYZ},{ankur23},{Richa25ABXabc#xyz.co}];
is their any way to get output like this in javascript, jquery, Angular.js.
Any other web used language is approved.
Check out this jsfiddle. You'll see both Array.prototype.reduce and Array.prototype.map used, both with the same results.
This is classic reduce:
var people = person.reduce(function(agg, p) {
return agg.concat([p.name + p.age + p.address]);
}, []);
The above uses Array.prototype.reduce.
In other words, when you want all the properties of an object or array "reduced" into something, then the most semantic go-to option is probably Array.prototype.reduce in this case.
However, Array.prototype.map can also do the job quite cleanly:
var people = person.map(function(p) {
return p.name + p.age + p.address;
});
This is an argument, now, between readability/complexity vs. semantics.
To limit incidental complexity (in the form of readability), I might go for the map function, even though you could argue this is technically a paradigmatic reduction.
Try this, this method suitable for different object names, it will work good.
var person = [
{name: 'saprsh', age: 22, address:'XYZ'},
{name: 'Ankur', age: 23},
{name: 'Richa', age:25, adddress:'ABX', email:'abc#xyz.co'}
];
var result = person.map(function(p){ return Object.keys(p).map(function(k){return p[k]}).join("");})
You can do it like this.
var person = [
{name: 'saprsh', age: 22, address:'XYZ'},
{name: 'Ankur', age: 23, address:'ABC'}
];
var test = person.map(function(one){
var properties = Object.getOwnPropertyNames(one);
return properties.map(function(prop){
return one[prop];
}).join('');
});
console.log(test);
I think it will help you.
var person = [
{name: 'saprsh', age: 22, address:'XYZ'},
{name: 'Ankur', age: 23, address:'ABC'}
];
var stringarray=[];
// $.each(person, function (i, d) {
// stringarray.push(d.name + d.age + d.address);
// });
//for(var i = 0; i < person.length; i++){
// stringarray.push(person[i].name + person[i].age + person[i].address);
//}
var stringarray = person.map(function(p) {
return p.name + p.age + p.address;
});
console.log(stringarray);
Result: ["saprsh22XYZ", "Ankur23ABC"]
Plz Try this one.
I assume you want a array of strings.
[{sparsh22XYZ},{ankur23ABC}]
is not such an array.
If you want
[ "sparsh22XYZ", "ankur23ABC" ]
you can simply go with
Plain old Javascript:
var string_person = [];
for (var i = 0; i < person.length; i++) {
string_person.push(person[i].name+person[i].age+person[i].address);
}
Underscore.js library
If all you need is a list of values of one of the object properties, it's easiest to go with underscore.js library.
var string_person = _.pluck(person, 'name');
http://underscorejs.org/#pluck
Call the below function on any array of Objects with any number of parameters, it will return you what you want.
function getStringArray(array){
var resultArray = [];
for (i = 0; i < array.length; i++) {
var result = "";
var keysArray = Object.keys(array[i]).sort()
for(j = 0; j < keysArray.length; j++){
result = result+array[i][keysArray[j]];
}
resultArray.push(result);
}
return resultArray;
}
var string_person = [];
for(var i = 0; i < person.length; i++){
string_person.push(person[i].name + person[i].age + person[i].address);
}
Updated:
Also You can use Underscore:
var string_person = _.map(person, function(p){return p.name + p.age + p.address;});
I guess you want to join all members of the object to a string. There are two ways to do this:
// iterate through the array of persons
for (var index = 0; index < person.length; index++) {
var obj = person[index]; // save the object temporally
person[index] = ''; // place an empty string at the index of the object
// iterate through all members of the object using the "in"-operator
for (var member in obj) {
person[index] += obj[member]; // add the value of the member to the string
}
}
The problem with this technique is, I cannot guarantee that it will join the values of the members in the order you want. It should join them in the order in which the members were defined.
Anyway this solution works fine but only in your case:
// iterate through the array of persons
for (var index = 0; index < person.length; index++) {
// place a string which contains the joined values of the members in the right order at the index of the object
person[index] = [
person[index].name,
person[index].age,
person[index].address
].join('');
}

Creating new object instances in a loop

I'm trying to create a new object for each item in an array by looping. The names of the objects should be based on the key of the array.
So for this array:
var arr = new Array(
"some value",
"some other value",
"a third value"
);
Would result in three objects:
alert(object1.value);
alert(object2.value);
alert(object3.value);
The code I have thus far (but isn't working) is:
// Object
function fooBar(value) {
this.value = value;
...
}
// Loop
var len = arr.length;
for (var i = 0; i < len; i++) {
var objectName = object + i;
var objectName = new fooBar(arr[i]);
}
Does what I'm asking for even make sense?
You have to make an array of the objects also
var objs = new Array();
for(var i = 0; i < len; i++) {
objs[i] = new fooBar(arr[i]);
}
alert(objs[0].value);
You can map your array:
var arr = new Array(
"some value",
"some other value",
"a third value"
);
var fooBars = arr.map(function(x) { return new fooBar(x); });
Then you can access each value:
alert(fooBars[0].value);
// etc.
or process them all at once:
fooBars.forEach(function (foo) { alert(foo.value); });
What you're asking for makes sense, but shouldn't be how you're building you JavaScript out.
Technically, there is a way of creating vars with names you build dynamically, but you shouldn't use it as it's slow, and if users are specifying what's in the array, it's unsafe and the feature is being needed in a couple of years, so your old stuff might break in future browsers.
Meanwhile, you could easily do something like:
var obj = {},
arr = [ "one", "two", "three" ],
i = 0,
len = arr.length,
val = "",
name = "";
for (; i < len; i += 1) {
name = "item" + i;
val = arr[i];
obj[name] = val;
}
Now you can call obj.item1; // "two"
If you're really desperate, you can use window as obj so when you're writing stuff in the global scope, you can just write item0; // "one" but this really isn't a great idea, for several reasons (readability, maintainability, likelihood of overwriting somebody else's properties, etc).
If you really want the variable named so, here's a solution
function fooBar(value) {
this.value = value;
}
var arr = new Array(
"some value",
"some other value",
"a third value"
);
(function(context) {
for ( var i = 0; i < arr.length; i++) {
var key = 'object' + ( i + 1 );
this[ key ] = new fooBar( arr[ i ] );
}
}(window));
alert(object1.value);
alert(object2.value);
alert(object3.value);
If you don't want global variables object1 ... just replace the keyword window with this and it will produce local variable to the current scope.
Test it out here: http://jsfiddle.net/bukart/F8ham/1/

How can I loop this (JSON)

{
"fulltime": [
{"name": "oscar godson", "age": "20", "email": "oscargodson#hismail.com"},
{"name": "daniel erickson", "age": "25", "email": "daniel#wraithtech.com"},
{"name": "john doe", "age": "18", "email": "john.doe#mycompany.com"}
],
"parttime":[
{"name": "bill johnson", "age": "35", "email": "billjohnson#gmail.com"}
]
}
and not knowing any of these values, e.g. fulltime could equal any thing. im looking for a function/method to loop through it all... Please, no jQuery.
Also, i want to basically get the output of: fulltime -> all inside of fulltime, parttime -> all inside of parttime, etc
for (key in your_object) {
console.log(key + " people:");
// "key" is "fulltime", "parttime", etc
for (var i = 0; i < your_object[key].length; i++) {
console.log(your_object[key][i]);
}
}
Supposing you have Firebug installed:
for(var key in json) {
//"fulltime", "parttime"
console.log("Checking " + key);
for(var i = 0; i < json[key].length; i++){
var person = json[key][i];
//Each person
for(var prop in person) {
console.log(prop + ": " + person[prop]);
}
}
}
Edit: Be careful that you don't iterate with for ... in ... over an array. To iterate over an array, use the "regular" way with for(var i = 0; i < array.length; i++){...}
You can do that with a recursive function. But you need to be careful about circular references. See example below:
var arr = [];
/**
* Gets the string representation of the specified object. This method is
* used for debugging
* #param {Object} Object to convert to string
* #return {String} The string representation of the object
*/
var toObjectSource = function(obj) {
if(obj === null) {
return "[null]";
}
if(obj === undefined) {
return "[undefined]";
}
var str = "[";
var member = null;
for(var each in obj) {
try {
member = obj[each];
if(arr.indexOf(member) === -1) { // the indexOf function is not available
// on older versions of js
arr.push(member);
str += each + "=" + toObjectSource(member) + ", "; // but beware of this
// recursive call!!!
}
}catch(err) {
alert(err);
}
}
return str + "]";
}
The reason for the check is that. It will give you "too much recursion" in case the object is like this:
var obj = {
"a": "a",
"b": "b"
}
obj.c = obj;
First of all you can verify your JSON data in http://www.jsonlint.com/.
If you not yet convert the string with JSON to the object you should use JSON.parse function from the web browser or from http://www.json.org/js.html to convert input string to the object.
For looping through the properties of a object you can use "for in" loop. It is generally always recommended to use this loop in the following form:
for (var name in myObject) {
if (myObject.hasOwnProperty(name)) {
// ....
}
}
(see for example http://www.jslint.com/lint.html#forin for the explanation). You should don't forget to declare name as var name either inside of for statement or somewhere before. If you forget this the variable will be interpret as a global and your code will run slowly.
Loop through element of an array in more effective with a standard for loop instead of "for in" loop. Moreover to receive more performance advantages you should always cache an index of a property used more as one time in a local variable. For example the the loop
for (var i = 0; i < your_object[key].length; i++) {
console.log(your_object[key][i]);
}
should be better rewritten as following:
var arr = your_object[key];
var len = arr.length;
for (var i = 0; i < len; i++) {
console.log(arr[i]);
}

JavaScript function, which reads connections between objects

I have a JavaScript literal:
var members = {
"mother": {
"name" : "Mary",
"age" : "48",
"connection": {
"brother" : "sun"
}
},
"father": {
"name" : "Bill",
"age" : "50"
},
"brother": {
"name" : "Alex",
"age" : "28"
}
}
Than I have a function, which should read connections from the literal above. It looks like this:
function findRelations(members){
var wires = new Array();
var count = 0;
for (n = 0; n < members.length; n++){
alert(members.length); // this alert is undefined
if (members[n].connection){
for (i = 0; i < members[n].connection[0].length; i++){
var mw = new Array();
var destination = 0;
for (m = 0; m < members.length; m ++){
if (members[m] == members[n].connection[0]){
destination = m;
mw = [n, destination];
wires [count] = mw;
count++;
}
}
}
}
}
return wires;
}
However, when I run this function, I get nothing. And the first alert, which is placed inside the function shows 'undefined' at all.
findRelations(members);
alert("Found " + wires.length + " connections");
I guess that's because of JavaScript literal. Could you suggest how to change a function or perhaps to change litteral to JSON array to get it work?! And at the end to get 'm' and 'n' values as numbers.
What is a 'literal'? I guess you mean 'an object created using the literal notation'.
Only Array's (and strings) have a length property, what you want is to loop through the properties
for (var prop in members) {
if (members.hasOwnProperty(prop)) {
alert("members has property " + prop);
}
}
This should get you on the right path as its not easy to follow the rest of the logic
The alert gives you "undefined" because your function seems to be expecting an array whereas your "members" variable is an Object.
the "length" property is not defined on an object. So,
var a = {
name:'test',
age:56
};
console.log(a.length); //undefined
The same is the reason for getting no response as well.

Categories