Lodash 映射到对象数组
Lodash map to array of objects
我从一个 jQuery 包装器开始,其中包含许多 <A>
-tag 元素。我想要的结果是:
[{href: "http://...", text: "The inner text"}, {...}, ...]
到目前为止我得到了这个:
_.map($pubs, ($pub) => _.pick($pub, 'href', 'innerText'))
可行,但看起来有更好的方法,内部文本 属性 被命名为 "innerText" 而不是 "text"。而且我确实想要元素的 innerText
而不仅仅是 .text()
因为它不会清理输出(换行符,空格,...)。
您可以使用 ES6 destructuring, and assign text
to a new variable. Now you can create a new object with the href
, and text
variables using 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>
我从一个 jQuery 包装器开始,其中包含许多 <A>
-tag 元素。我想要的结果是:
[{href: "http://...", text: "The inner text"}, {...}, ...]
到目前为止我得到了这个:
_.map($pubs, ($pub) => _.pick($pub, 'href', 'innerText'))
可行,但看起来有更好的方法,内部文本 属性 被命名为 "innerText" 而不是 "text"。而且我确实想要元素的 innerText
而不仅仅是 .text()
因为它不会清理输出(换行符,空格,...)。
您可以使用 ES6 destructuring, and assign text
to a new variable. Now you can create a new object with the href
, and text
variables using 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>