2017-06-23 100 views
0

嗨我有解析數據的大問題。我有結構是這樣的:解析JSON到數組

<code> 
[{ 
    "absent": ["a", "b", "c"], 
    "against": ["a", "b", "c"], 
    "club": "club1", 
    "for": ["a", "b", "c"], 
    "withhold": ["a", "b", "c"] 
}, { 
    "absent": ["a", "b", "c"], 
    "against": ["a", "b", "c"], 
    "club": "club2", 
    "for": ["a", "b", "c"], 
    "withhold": ["a", "b", "c"] 
}, { 
    "absent": ["a", "b", "c"], 
    "against": ["a", "b", "c"], 
    "club": "club3", 
    "for": ["a", "b", "c"], 
    "withhold": ["a", "b", "c"] 
}] 
</code> 

,我需要解析此結構陣列像這樣的:

<code> 
    array={a,"absent",clube1 
    b,absent,clube1 
    c,absent,clube1 
    a,against,clube1 
    b,against,clube1 
    c,against,clube1 
    a,for,clube1 
    b,for,clube1 
    c,for,clube1 
    a,withhold,clube1 
    b,withhold,clube1 
    c,withhold,clube1 

    a,absent,clube2 
    b,absent,clube2 
    c,absent,clube2 
    a,against,clube2 
    b,against,clube2 
    c,against,clube2 
    a,for,clube2 
    b,for,clube2 
    c,for,clube2 
    a,withhold,clube2 
    b,withhold,clube2 
    c,withhold,clube2 
    } 
</code> 

等等 任何人可以幫助我嗎?我正在使用純Java腳本。我不能改變這個結構,所以只有一種方法是編寫代碼來排序。感謝您的幫助和對我的英語感到抱歉。

+0

您忘記添加你試過到目前爲止javascript代碼! –

+0

看起來像[Array#reduce](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce)的東西,但你的嘗試和問題在哪裏? – Xotic750

+0

爲什麼你所期望的結構在字符串周圍沒有引號? – Barmar

回答

0

這應該做的伎倆,它基本上映射在整個結構:

data.map((el) => 
    Object.keys(el) 
     .filter((key) => key !== "club") 
     .map((key) => el[key].map((v) => [v, key, el["club"]])) 
).join() 

對於OP的其他格式:

data.map((el) => 
    Object.keys(el) 
     .filter((key) => key !== "club") 
     .map((key) => el[key].map((v) => [v, key, el["club"]])) 
).reduce((arr, el) => arr.concat(el.reduce((x, a) => x.concat(a), [])), []) 
+0

您是AWESOM!謝謝 !!工作完美卡爾德你給我一個更多的反饋?我給錯了結構,如何改變你的代碼給我結構作爲數組不是字符串[0] .name.vote.club有一個愉快的週末謝謝! – breakbit

+0

如果你的意思是有一個數組數組,其中每個數組有三個元素,第二個應該工作 - 代碼有點奇怪,可能是一個更簡單的方式:) – jackarms

+0

第二個代碼存在問題未捕獲TypeError:el [key] .map不是一個函數。你很棒 !感謝您的支持。 – breakbit

0
var arr = [{ 
    "absent": ["a", "b", "c"], 
    "against": ["a", "b", "c"], 
    "club": "club1", 
    "for": ["a", "b", "c"], 
    "withhold": ["a", "b", "c"] 
}, { 
    "absent": ["a", "b", "c"], 
    "against": ["a", "b", "c"], 
    "club": "club2", 
    "for": ["a", "b", "c"], 
    "withhold": ["a", "b", "c"] 
}, { 
    "absent": ["a", "b", "c"], 
    "against": ["a", "b", "c"], 
    "club": "club3", 
    "for": ["a", "b", "c"], 
    "withhold": ["a", "b", "c"] 
}]; 

//console.log(arr); 
var arr2 = []; 
for(var i = 0; i < arr.length; i++) { 
    var ab = arr[i].absent; 
    for (var key in arr[i]) { 
     if (arr[i].hasOwnProperty(key)) { 
      for(var j = 0; j < ab.length; j++) { 
       arr2.push(ab[j], key, arr[i].club); 
      } 
     } 
    } 
} 
//console.log("2: ", arr2);