2017-02-11 58 views
0

我的JavaScript樹對象,我想將它轉化成列出陣列從javascript樹對象創建列表數組?

我的樹:

[https://jsfiddle.net/wahmal/f2pcmptt/][1] 

如何讓「href」屬性值,並將它推到一個數組列表?

var res=['hrefValue','hrefValue','hrefValue','hrefValue','hrefValue','hrefValue']; 
+0

你能告訴我們更多關於你的問題? – WitVault

+0

JavaScript沒有數組列表,但它具有類似功能的數組。 –

+0

另外,你爲什麼要試圖把這個包裝成單個數組項,然後用''[{...}]'來包裝成一個字符串?刪除引號''[....]'',''引號不支持多行字符串,並且沒有理由這樣做。它不被支持是一個很大的字符串,如果你喜歡它,它將不會正常運行。 –

回答

1
function convert(tree){ 
    return tree.reduce(function(acc, o) {  // check the docs for reducs in the link bellow 
     if(o.href)        // if this object has an href 
      acc.push(o.href);     // add the href to the result array 
     if(o.nodes)        // if this object has children 
      acc = acc.concat(convert(o.nodes)); // get their href and add (concat) them to the result 
     return acc; 
    }, []); 
} 
  • tree應的陣列不是字符串,如果它作爲一個字符串(JSON字符串),那麼你必須將它傳遞給使用JSON.parse函數之前解析它。

  • Javascript沒有ArrayLists,它只有數組。

  • 這裏是Array.prototype.reduce的文檔的鏈接。

  • 這是一個工作fiddle

+0

whoaaa thnks @ibrahim,你救了我一天! – wahmal

1
var getHrefs = function(nodes) { 
    return nodes.reduce(function (arr, node) { 
     return arr.concat(node.href).concat(node.nodes ? getHrefs(node.nodes) : []); 
    }, []); 
} 

var hrefs = getHrefs(tree); // ["7400.34.03.00.00.00", "7400.34.03.01.00.00", ... etc.] 
+0

請提供一些關於你的問題的解釋,代碼只有答案沒有那麼有用。 – Arman

1

您可以使用Array.prototype.map(),展布元件

let res = []; 
tree.map(({href, nodes}) => res = [...res, href, ...nodes.map(({href:h}) => h)]); 
// do stuff with `res` 

的jsfiddle https://jsfiddle.net/4ajr1spr/