2017-10-19 322 views
0

我從一個包含<A> -tag元素的jQuery包裝器開始。我想結果是:Lodash映射到對象數組

[{href: "http://...", text: "The inner text"}, {...}, ...] 

到目前爲止,我得到這個:

​​

這樣的作品,但它看起來像有一個更好的方式,和內text屬性被命名爲「的innerText」,而不是「文本」。我確實需要innerText的元素,而不是.text(),因爲它不會清理輸出(換行符,空格,...)。

回答

1

您可以使用ES6 destructuringassign text to a new variable。現在你可以創建一個新的對象與href,並text變量使用shorthand property names

const links = $('a').toArray(); 
 

 
const result = links.map(({ href, innerText: text }) => ({ href, text })); 
 

 
console.log(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<a href="http://www.google.com">Google</a> 
 
<a href="http://www.facebook.com">Facebook</a> 
 
<a href="http://www.apple.com">Apple</a>

你也可以使用jQuery的'.map()`

const result = $('a').map((k, { href, innerText: text }) => ({ href, text })).toArray(); 
 

 
console.log(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<a href="http://www.google.com">Google</a> 
 
<a href="http://www.facebook.com">Facebook</a> 
 
<a href="http://www.apple.com">Apple</a>

+0

我在使用Babel編譯ES6時, d我想這裏有個bug,因爲它將'map'語句編譯爲:'return pubs.map(function(_ref){var href = _ref.href,text = _ref.innerText;返回{href:href,text:text}; });''但'_ref'是'map'方法中的索引參數,而不是值。任何想法如何解決? – Koen

+1

第一個參數是Array#map中的值。你在jQuery對象上使用'.toArray()'嗎? –

+0

對!我正在使用一個使用大量鏈接的框架,並且顯然在每一步中都會將一組元素重新轉換爲一個jQuery包裝器,所以我的'toArray'調用沒有效果。 – Koen