Martijn van der Jagt
Martijn van der Jagt

Reputation: 524

Accessing a javascript object in D3.js

A javascript data object (JSON notation) has been created with the following content:

"[
   {"range":"Shape","values":[{"idx":0,"val":"Random"},{"idx":1,"val":"Line"},{"idx":2,"val":"Square"},{"idx":3,"val":"Circle"},{"idx":4,"val":"Oval"},{"idx":5,"val":"Egg"}]},
   {"range":"Color","values":[{"idx":0,"val":"Red"},{"idx":1,"val":"Blue"},{"idx":2,"val":"Yellow"},{"idx":3,"val":"Green"},{"idx":4,"val":"Cyan"}]}
]"

In a next step the index of an ordinal value has to be found in this object. The function should find the index of the value 'Blue' in the range 'Color'.

So the function should have the meta scripting form

f("Color")("Blue")=1

What is the most elegant form to create such a function in the context of D3 and javascript?

Upvotes: 0

Views: 286

Answers (2)

Felix Kling
Felix Kling

Reputation: 816442

Depending on your use case, it might make sense to convert the data structure to a different structure more suitable for direct access. E.g. you could convert your structure to

var data = {
    Shape: ['Random', 'Line', ...], 
    // ...
};

and access it with

data['Shape'].indexOf('Line') // or data.Shape.indexOf('Line')

Or go even one step further and convert to

var data = {
    Shape: {
      Random: 0,
      Line: 1, 
      // ...
    },
    // ...
};

and access it with

data['Shape']['Line'] // or data.Shape.Line

What the best solution is depends on the actual use case.


Converting the structure dynamically is pretty straight forward. Here is an example to convert it to the first suggestion:

var newData = {};
data.forEach(function(item) {
    newData[item.range] = 
        item.values.map(function(value) { return value.val; });
});

This would also reduce redundancy (e.g. idx seems to correspond with the element index).

Upvotes: 2

Alp
Alp

Reputation: 3105

Would this work for you ?

var dataJson = '[ \
   {"range":"Shape","values":[{"idx":0,"val":"Random"},{"idx":1,"val":"Line"},{"idx":2,"val":"Square"},{"idx":3,"val":"Circle"},{"idx":4,"val":"Oval"},{"idx":5,"val":"Egg"}]},\
   {"range":"Color","values":[{"idx":0,"val":"Red"},{"idx":1,"val":"Blue"},{"idx":2,"val":"Yellow"},{"idx":3,"val":"Green"},{"idx":4,"val":"Cyan"}]}\
]';

var data = JSON.parse(dataJson);

for (each in data){
   if ( (data[each].range) === 'Color'){
      for (eachVal in data[each].values){
         if (data[each].values[eachVal].val === 'Blue'){
            alert(data[each].values[eachVal].idx);
         }
      }
   } ;
}

And here is the JSFiddle for you too.

Upvotes: 0

Related Questions