JavaScript function, which reads connections between objects - javascript

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.

Related

Key value paired array element returns "undefined" error while it is assigned the value in given index javascript

I need four key/value paired arrays for my code and I decrement the value for each array based on conditions.
In checking if the given value is bigger than 0 I randomly get "undefined" error in each of the four arrays and I do not know how to fix this problem
Here is my code:
Asett=[
"A" ,
"B",
"C"
]
var Bset = [
"D",
"E",
"F"
];
var Cset = [
"G" ,
"H",
"I"
];
var Dset = [
"J",
"K",
"L"
];
var cSets = [];
var vSets=[];
var dSets=[];
var fSets=[];
function initiate(){ //this function initiates the given arrays with defined elements and value equal to 10
for (var iv=0;iv<3;iv++){
cSets.push({
key: Asett[iv],
rem:10
})
}
for (var iv=0;iv<3;iv++){
vSets.push({
key: Bset[iv],
rem:10
})
}
for (var iv=0;iv<3;iv++){
dSets.push({
key: Cset[iv],
rem:10
})
}
for (var iv=0;iv<3;iv++){
fSets.push({
key: Dset[iv],
rem:10
})
}
}
initiate();
generateList(cSets,vSets,dSets,fSets);
function generateList(cSets,vSets,dSets,fSets){
var j=0;
var k=0;
var l=0;
var m=0;
var taskL = []; // create an empty array
var f=0;
for (var i=0; i<27;i++){
j=getRndInteger(0,2);
k=getRndInteger(0,2);
l=getRndInteger(0,2);
m=getRndInteger(0,2);
var combinations="";
while (cSets[j].rem<=0) // I get cSets[j] undefined error
{
j=(j % 3) +1;
}
combinations+=comSets[j].key+",";
comSets[j].rem--;
while (vSets[k].rem<=0) //I get vSets[k] undefined error
{
k=(k % 3) +1;
}
combinations+=vSets[k].key+",";
vSets[k].rem--;
while (dSets[l].rem<=0) //I get dSets[l] undefined error
{
l=(l % 3) +1;
}
combinations+=changeSets[l].key+",";
changeSets[l].rem--;
while (fSets[m].rem<=0) //I get fSets[m] undefined error
{
m=(m % 3) +1;
}
combinations+=fSets[m].key+",";
fSets[m].rem--;
taskL[f++]=combinations;
}
}
In this code I expect my taskL array to get the combinations however I randomly recieve undefined error for each of the given sets (cSets, vSets, dSets and fSets) even though they are assigned value. Any help would be appreciated
You have to change all of j=(j % 3) +1; these into j=(j+1) % 3
This way when your j is 2, it will be +1 and it will be 3 then %3 it will be 0 so you would not get out of bound exception.

i want "code" =10 change into "code"= "10" in JavaScript object

[{"code":10,"shtdesc":"CoOrdHR","name":"CO-ORDINATOR - HR","isselect":0}]
change
(int to string)=> particular value "code"=10-> "code"="10" , "isselect":0->"isselect":"0"
I want output to be
[{"code":"10","shtdesc":"CoOrdHR","name":"CO-ORDINATOR - HR","isselect":"0"}]
Try the following:
var data = [{"code":10,"shtdesc":"CoOrdHR","name":"CO-ORDINATOR - HR","isselect":0}];
data[0].code = String(data[0].code);
If you want to change all properties to strings, in all elements of the array, then
function change_properties_to_strings(arr) {
return arr.forEach(function(obj) {
Object.keys(obj).forEach(function(key) {
obj[key] = String(obj[key]);
});
});
}
In other words, loop over the elements of the array, each of which is an object. For each object, loop over its keys (property names). For each key, change the value of the that property to a string.
If you prefer for-loops, using the same logic you can write:
function change_properties_to_strings(arr) {
for (var i = 0; i < arr.length; i++) {
var obj = arr[i];
for (var k in obj) {
obj[k] = String(obj[k]);
}
}
}
In Java:
I would remove all opening and close brace/brackets then split by ",|:". Iterate through the array, from the split, adding quotes around a value if they're not there, while adding them back to a newly constructed json String.
Example:
public static void main(String[] args) throws Exception {
String json = "[{\"code\":10,\"shtdesc\":\"CoOrdHR\",\"name\":\"CO-ORDINATOR - HR\",\"isselect\":0}]";
// Split out each value
String[] jsonPieces = json.replaceAll("[\\[\\]{}]", "").split(",|:");
// Reconstruct json
StringBuilder sb = new StringBuilder("[{");
for (int i = 0; i < jsonPieces.length; i++) {
// Add quotes if they're not there
if (!jsonPieces[i].startsWith("\"")) {
jsonPieces[i] = "\"" + jsonPieces[i] + "\"";
}
// Append json piece
sb.append(jsonPieces[i]);
// Append ":" or ","
if (i + 1 < jsonPieces.length) {
sb.append(i % 2 == 0 ? ":" : ",");
}
}
// Append closing
sb.append("}]");
// Reassign back to json
json = sb.toString();
// Display results
System.out.println(json);
}
Results:
[{"code":"10","shtdesc":"CoOrdHR","name":"CO-ORDINATOR - HR","isselect":"0"}]
Try this example
var arr = [{
"code": 10,
"shtdesc": "CoOrdHR",
"name": "CO-ORDINATOR - HR",
"isselect": 0
}];
alert(JSON.stringify(arr));
var transform = function(list) {
var l = list.length;
var o;
while (l--) { //loop through each json
o = list[l];
for (var k in o) // loop through each key in json
if ('number' === (typeof o[k])) // only if property value is number
o[k] = o[k].toString();
}
return list;
};
alert(JSON.stringify(transform(arr)));

Javascript arrays as objects [duplicate]

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("];");

JSON count an Array elements and wrap in

Well I've just discovered JSON today but I have a problem using it correctly. I really can't find a solution...
Basically, I just want to count the elements of my array (count all the dM), and wrap on a specific element (dM1 for example).
Here is my code so that you can understand: http://jsfiddle.net/dRycS/9/
Adding to what #Pointy said here is your code modified:
JSFiddle Demo
Object.size = function(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
var dMContent = {
"dM1" : [
{
"name" : "EeEeEeEe",
"link" : "http://test.com"
},
{
"name" : "FfFfFfFf",
"link" : "http://test.com"
},
{
"name" : "GgGgGgGg",
"link" : "http://test.com"
}
],
"dM2" : [
{
"name" : "EeEeEeEe",
"link" : "http://test.com"
},
{
"name" : "FfFfFfFf",
"link" : "http://test.com"
}
],
"dM3" : [
{
"name" : "EeEeEeEe",
"link" : "http://test.com"
}
]
};
var STORAGE = JSON.stringify(dMContent);
var parsed = JSON.parse(STORAGE);
// WHAT I WANT TO DO
// Count the number of dM
console.log(Object.size(parsed)); //gives you 3
//display the content
for(var i in parsed){
console.log('data in ' + i);
for(var j=0; j<parsed[i].length; j++){
console.log(parsed[i][j].name + ' ' + parsed[i][j].link);
}
}
What you've got there is not an Array; it's an Object. Array objects do have a "length" property, but Objects do not.
It's not clear exactly what you want; if you wanted to count every property of every object inside of "dMContent", you'd write something to count recursively. For a single "layer" of an object, something like this might be what you want:
function objectSize(obj) {
var count = 0;
for (var k in obj) {
if (obj.hasOwnProperty(k)) ++count;
}
return count;
}
In your code dMContent is an Object, not an Array.
To count elements in an Object, do this:
var i = 0;
for (x in parsed) {
if (parsed.hasOwnProperty(x)) {
i++;
}
}
alert(i);
Try this:
function objectCount(obj) {
objectcount = 0;
$.each(obj, function(index, item) {
objectcount = objectcount + item.length;
});
return objectcount;
}
objectCount(obj);
where obj is a json object with json array as sub objects

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]);
}

Categories