2013-08-26 3 views
0

개체의 키와 값에 액세스하려고 시도하는 동안 undefined이 나타납니다. 다음은 내 코드개체의 키와 값 얻기

<script type="text/javascript"> 

var data; 
var xAxisName; 
var yAxisName; 
var jso; 

function getX(d) { 
    return d[xAxisName]; 
      } 
function getY(d) { 
    return d[yAxisName]; 
      } 
d3.json("response.json", function (json) { 

console.log("hi"); 
console.log(json);    //getting the values 
console.log("this " +json.users); //getting the values 
xAxisName = json.attribute1.; 
console.log("xAxisName=" + xAxisName); //Not getting the values 
yAxisName = json.attribute2; 
console.log("yAxisName=" + yAxisName); //Not getting the values 
data = json.users; 
alert(data); 

data.map(function(d) { console.log(getX(d));}); 
data.map(function(i) {console.log(i);}); 
visualize(data); //then start the visualization 
}); 

function visualize (data) { 

var padding = 40; 
var margin = {top:30, right: 30, bottom: 30, left:100}; 
var w = 700 - margin.left - margin.right; 
var h = 400 - margin.top - margin.bottom; 

//the svg 
var svg = d3.select("#container") 
.append("svg") 
.attr("class", "chart") 
.attr("width", w + margin.left + margin.right) 
.attr("height", h + margin.top + margin.bottom) 
.append("g") 
.attr("transform", "translate(" + margin.left + "," + margin.top + ")"); 

//the scales 
var xScale = d3.scale.ordinal() 
.domain(d3.range(data.length)) 
.rangeRoundBands([0, w], 0.04); 

var yScale = d3.scale.linear() 
.domain([d3.max(data, getY), 0]) 
.range([0, h]); 

//the axes 
var xAxis = d3.svg.axis().scale(xScale).orient("bottom"); 
var yAxis = d3.svg.axis().scale(yScale).orient("left"); 

//add the data and bars 

svg.selectAll("rect") 
.data(data) 
.enter() 
.append("rect") 
.attr("x", function(d, i) { return xScale(i);}) 
.attr("y", function(d) { return yScale(getY(d));}) 
.attr("width", xScale.rangeBand()) 
.attr("height", function(d) { 
return h - yScale(getY(d));}) 
.attr("class", "bar"); 

//create axes 

svg.append("g").attr("class", "x axis") 
       .attr("transform", "translate(0," + h + ")").call(xAxis); 

svg.append("g").attr("class", "y axis") 
       .call(yAxis) 
       .append("text") 
       .attr("transform", "rotate(-90)") 
       .attr("y", 6) 
       .attr("dy", ".71em") 
       .style("text-anchor", "end") 
        .text(yAxisName); 
          } 
      alert("done"); 
     </script> 

그것은 xAxisNameyAxisName에 대한 undefined을주고있다. yheight의 경우는 NaN입니다.

내 JSON은 그것은 당신이 사용자 개체의 속성 이름을 추출 할 좋아 보이는

{ 

"users": [ 
    { 
     "name": "warchicken", 
     "score": 30 
    }, 
    { 
     "name": "daydreamt", 
     "score": 100 
    }, 
    { 
     "name": "Anas2001", 
     "score": 30 
    }, 
    { 
     "name": "ocjojo", 
     "score": 30 
    }, 
    { 
     "name": "joklawitter", 
     "score": 30 
    } 
] 
} 
+0

xAxisName = json.attribute1 .; 이 줄의 끝 부분에 여분의 점이 있습니다. 문제가있는 것이 확실하지 않은 경우 ... – kangoroo

+0

Json 개체에 attribute1 및 attribute2와 같은 것 외에는 아무 것도 없습니다. json.attribute1에서 원하는 값은 무엇입니까? 올바른 작업이 아닙니다. –

+0

도 마찬가지입니다. json.users.name, json.users.score json을 실제로 사용한 적이 없지만 – kangoroo

답변

0

입니다. 이를 수행하려면 Object.keys()을 사용하거나 for...in (관련 질문 : How do I enumerate the properties of a JavaScript object?) 개체를 반복 할 수 있습니다.

var keys = Object.keys(json.users[0]); 
xAxisName = keys[0]; 
yAxisName = keys[1]; 

개체 속성이 정렬되지 않지만주의하십시오. 결국 xAxisName"score"이고 그 반대의 경우도 마찬가지입니다.

xAxisName이 특정 값인 경우 하드 코드하거나 서버에서 반환하는 JSON에 정보를 추가해야합니다. 예를 들어 :

{ 
    "axes": ["name", "score"], 
    "users": [...] 
} 

은 그럼 당신은

xAxisName = json.axes[0]; 
// ... 

사이드 메모와 함께 그것을 얻을 : 개체에 대한 변수 이름으로 json을 선택하는 것은 최적이 아닌이 변수가 JSON을 포함하는 문자열을 보유하고 있음을 알 수 있기 때문에 , 실제로는 객체를 보유하고 있습니다. 대체로 chartData은 어떨까요?

+0

이제 다른 문제가 있습니다. 내 그래프는 x 축보다 100px 아래에서 시작됩니다. 그래프를 X 축에서 시작하도록 설정하는 방법. –

+0

스스로 해결할 수없는 새로운 문제가있는 경우 새로운 질문을해야합니다. –