2015-01-02 20 views
-2

我有以下数据结构:循环通过数据结构中的CoffeeScript

{ 
data: [ 
    { 
     id: 5, 
     name: 'ItemOne' 
    }, 
    { 
     id: 14, 
     name: 'ItemTwo' 
    }, 
    { 
     id: 15, 
     name: 'ItemThree' 
    } 
] 

}

而且我想通过它循环,但我挣扎。我试过了:

for result,value of results 
    console.log results 
    item = 0 
    message = "Component: " + value[item]['name'] + " Status: " + value[item]['status'] 
    output.push message 
    item++ 

但它只返回一个结果。我显然已经离开了,但我需要做什么?

+2

你所示的数据结构是无效的,它有很多错误。 – thefourtheye

+0

Json语法错误。写入有效的json。 – sandipon

+0

我更新了数据结构,我不得不修改原来的内容,并且没有错误检查它 – jaxxstorm

回答

0

您应该通过.data迭代。这里是一个完全工作的例子:http://jsfiddle.net/hd4ru1kf/5/


最初的问题也有与数据符号

您可以从学习CoffeeScript JSON notation here受益的问题。

kids = 
    brother: 
    name: "Max" 
    age: 11 
    sister: 
    name: "Ida" 
    age: 9 

编译为:

kids = { 
    brother: { 
    name: "Max", 
    age: 11 
    }, 
    sister: { 
    name: "Ida", 
    age: 9 
    } 
}; 

在你的榜样,你有,字符是无效的,整个JSON结构的路要走。你也笨拙地嵌套了JSON,也许你不想要那个?相反,我认为这是你正在寻找(你可以用http://coffeescript.org/检查出来)的工作版本:

data: 
    [ 
     { 
      id: 1 
      name: "Item one" 
     } 
     { 
      id: 2 
      name: "Item two" 
     } 
     { 
      id: 3 
      name: "Item three" 
     } 
    ] 
+0

是的,这是正确的结构,谢谢指出。我的问题是我试图通过它来循环使用键/值符号正确地获取元素? – jaxxstorm

+0

这是否解决了您的问题?它在这里工作(你也没有深入你的代码):http://jsfiddle.net/hd4ru1kf/3/ – Sampsa

+0

似乎并没有这样做,我错过了一种获取数组键的方法(即0,1,2) – jaxxstorm