Nag Nag - 3 months ago 7
CoffeeScript Question

How to get json name values on iteration instead of indexes or ids?

I have the following json:

var testjson = {
"Mytest": [{
"Testing": {
"static": {
"name": "first name"
},
"key1": "key1 val",
"key2": 10

}
}, {
"Testing": {
"static": {
"name": "second name"
},
"key3": 20,
"key4": true


}
}, {
"Testing": {
"static": {
"name": "third name"
},
"key5": "key5 val"

}
}]
}


I have the following coffeescript: @
itemNames = (item for item of @mydata).sort (a,b) -> a>b
, but I changed it to the following javascript conversion:

var mydata = testjson.Mytest;
var item;

this.itemNames = ((function() {
var results;
results = [];
for (item in mydata) {
results.push(item);
}
return results;
}).call(this)).sort(function(a, b) {
return a > b;
});
console.log(mydata);//gives: [Object, Object, Object]
console.log(this.itemNames);//gives: ["0", "1", "2"], but I need it like: ["first name", "second name", "third name"], how can I get it ?


Here I am getting the output in my console as:
["0", "1", "2"]
, but I need it like:
["first name", "second name", "third name"]
, and of course if I expand it on the console, it should display those values(like:
0: "first name", 1: "second name", 2: "third name"
). Created Fiddle.


Please, help me that how to get those names and thanks in advance.

Answer

You can do like this.Your item is the index of the element.Your need to get the element at the index, then access to property name via Testing.static.name.

this.itemNames = ((function() {
  var results;
  results = [];
  for (item in mydata) {
    results.push(mydata[item].Testing.static.name);
  }
  return results;
}).call(this)).sort(function(a, b) {
  return a > b;
});

This is the code.

var testjson = {
    "Mytest": [{
        "Testing": {
            "static": {
                "name": "first name"
            },
            "key1": "key1 val",
            "key2": 10

        }
    }, {
        "Testing": {
            "static": {
                "name": "second name"
            },
            "key3": 20,
            "key4": true


        }
    }, {
        "Testing": {
            "static": {
                "name": "third name"
            },
            "key5": "key5 val"

        }
    }]
};


var mydata = testjson.Mytest;
var item;

this.itemNames = ((function() {
  var results;
  results = [];
  for (item in mydata) {
    results.push(mydata[item].Testing.static.name);
  }
  return results;
}).call(this)).sort(function(a, b) {
  return a > b;
});

console.log(this.itemNames);