81

How can I get the name and value of each object in Javascript only?

Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
Parekh Shah
  • 69
  • 2
  • 5
  • 9

4 Answers4

154

There are two ways to access properties of objects:

var obj = {a: 'foo', b: 'bar'};

obj.a //foo
obj['b'] //bar

Or, if you need to dynamically do it:

var key = 'b';
obj[key] //bar

If you don't already have it as an object, you'll need to convert it.

For a more complex example, let's assume you have an array of objects that represent users:

var users = [{name: 'Corbin', age: 20, favoriteFoods: ['ice cream', 'pizza']},
             {name: 'John', age: 25, favoriteFoods: ['ice cream', 'skittle']}];

To access the age property of the second user, you would use users[1].age. To access the second "favoriteFood" of the first user, you'd use users[0].favoriteFoods[2].

Another example: obj[2].key[3]["some key"]

That would access the 3rd element of an array named 2. Then, it would access 'key' in that array, go to the third element of that, and then access the property name some key.


As Amadan noted, it might be worth also discussing how to loop over different structures.

To loop over an array, you can use a simple for loop:

var arr = ['a', 'b', 'c'],
    i;
for (i = 0; i < arr.length; ++i) {
    console.log(arr[i]);
}

To loop over an object is a bit more complicated. In the case that you're absolutely positive that the object is a plain object, you can use a plain for (x in obj) { } loop, but it's a lot safer to add in a hasOwnProperty check. This is necessary in situations where you cannot verify that the object does not have inherited properties. (It also future proofs the code a bit.)

var user = {name: 'Corbin', age: 20, location: 'USA'},
    key;

for (key in user) {
    if (user.hasOwnProperty(key)) {
        console.log(key + " = " + user[key]);
    }
}    

(Note that I've assumed whatever JS implementation you're using has console.log. If not, you could use alert or some kind of DOM manipulation instead.)

Community
  • 1
  • 1
Corbin
  • 33,060
  • 6
  • 68
  • 78
21

Try the JSON Parser by Douglas Crockford at github. You can then simply create a JSON object out of your String variable as shown below:

var JSONText = '{"c":{"a":[{"name":"cable - black","value":2},{"name":"case","value":2}]},"o":{"v":[{"name":"over the ear headphones - white/purple","value":1}]},"l":{"e":[{"name":"lens cleaner","value":1}]},"h":{"d":[{"name":"hdmi cable","value":1},{"name":"hdtv essentials (hdtv cable setup)","value":1},{"name":"hd dvd \u0026 blue-ray disc lens cleaner","value":1}]}'

var JSONObject = JSON.parse(JSONText);
var c = JSONObject["c"];
var o = JSONObject["o"];
Sachin Sharma
  • 585
  • 1
  • 5
  • 16
8

Ok, here is the JS code:

var data = JSON.parse('{"c":{"a":{"name":"cable - black","value":2}}}')

for (var event in data) {
    var dataCopy = data[event];
    for (data in dataCopy) {
        var mainData = dataCopy[data];
        for (key in mainData) {
            if (key.match(/name|value/)) {
                alert('key : ' + key + ':: value : ' + mainData[key])
            }
        }
    }
}​

FIDDLE HERE

palaѕн
  • 72,112
  • 17
  • 116
  • 136
5
var yourobj={
"c":{
    "a":[{"name":"cable - black","value":2},{"name":"case","value":2}]
    },
"o":{
    "v":[{"name":"over the ear headphones - white/purple","value":1}]
},
"l":{
    "e":[{"name":"lens cleaner","value":1}]
},
"h":{
    "d":[{"name":"hdmi cable","value":1},
         {"name":"hdtv essentials (hdtv cable setup)","value":1},
         {"name":"hd dvd \u0026 blue-ray disc lens cleaner","value":1}]
}}
  • first of all it's a good idea to get organized
  • top level reference must be a more convenient name other that a..v... etc
  • in o.v,o.i.e no need for the array [] because it is one json entry

my solution

var obj = [];
for(n1 in yourjson)
    for(n1_1 in yourjson[n])
        for(n1_2 in yourjson[n][n1_1])
            obj[n1_2[name]] = n1_2[value];

Approved code

for(n1 in yourobj){
    for(n1_1 in yourobj[n1]){
    for(n1_2 in yourobj[n1][n1_1]){
            for(n1_3 in yourobj[n1][n1_1][n1_2]){
      obj[yourobj[n1][n1_1][n1_2].name]=yourobj[n1][n1_1][n1_2].value;
            }
    }
 }
}
console.log(obj);

result

*You should use distinguish accessorizes when using [] method or dot notation

proove

Rami Jamleh
  • 1,819
  • 1
  • 13
  • 10
  • 2
    This does not answer the question, is more or less a list of subjective opinions and you are wrong in your last point. – Felix Kling Dec 25 '12 at 06:54
  • last point isn't a point it's a recommendation of me and i am not wrong in that bacause not knowing a exact structure of arrays etc is a big problem mentioned in **OO** – Rami Jamleh Dec 25 '12 at 07:07
  • The JSON is clearly consistently structured. Top level object, where each property is another object, where each property is an array. How is this not hierarchical? – Felix Kling Dec 25 '12 at 07:09
  • no it is hierarchical but what is the type of object your handling and it's not clear why things put in that way and for what reason – Rami Jamleh Dec 25 '12 at 07:13
  • (well, you said it's not hierarchical in your answers...) It's a plain object. It's just a container for `key -> value` pairs. That's all you have to know. You don't need to know the property names, you just iterate over all with `for...in`. It is possible to access the information in this data structure dynamically, so I don't understand why you see a problem here. – Felix Kling Dec 25 '12 at 07:14
  • i don't see a problem but things put that way are really defficult for maintenance and testing – Rami Jamleh Dec 25 '12 at 07:18
  • Maybe... but if the data e.g. comes from a third party service, you don't have control over it anyway. Your answer reads like *"I don't explain how to process this data because I disagree with its structure"*, which is not really helpful. Pointing out the, in your eyes, unusual structure is rather more appropriate as a comment than an answer. – Felix Kling Dec 25 '12 at 07:23
  • i said *in even hierarchy manner* meaning it's not clear what elements have more or less json entry in it object i is not formed like c and o – Rami Jamleh Dec 25 '12 at 07:26
  • `i`? Did you mean `l`? And yes, the structure is the same. Look at the question! In your answer, you just formatted the code wrongly (there is a closing bracket after `e`, `h` and `l` are at the same level). – Felix Kling Dec 25 '12 at 07:28
  • Sorry i did not c that i thought e and h are object in l(thought it was an i) and i did something hope you like it – Rami Jamleh Dec 25 '12 at 07:52
  • 1
    Thanks for updating your answer, but your solution is incorrect. I recommend to test it at http://jsfiddle.net/ first. – Felix Kling Dec 25 '12 at 07:54