0

I'm starting from a jQuery wrapper with a number of <A>-tag elements in it. The result I want is:

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

Thus far I got this:

_.map($pubs, ($pub) => _.pick($pub, 'href', 'innerText'))

That works, but it looks like there's a better way, and the inner text property is named "innerText" instead of "text". And I do want the innerText of the elements and not just the .text() as that doesn't clean up the output (newlines, whitespace,...).

1 Answer 1

1

You can use 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>

You can also use jQuery's '.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>

Sign up to request clarification or add additional context in comments.

4 Comments

I'm using Babel compiled ES6, and I guess there's a bug there as it compiles the map statement to: return pubs.map(function (_ref) { var href = _ref.href, text = _ref.innerText; return { href: href, text: text }; }); but _ref is the index argument in the map method, not the value. Any idea on how to resolve that?
The 1st param is the value in Array#map. Did you use .toArray() on the jQuery object?
Right! I'm using a framework that uses a lot of chaining and apparently reconverts an array of elements to a jQuery wrapper in each step, so my toArray call had no effect.
The little annoying things in life :) I've also added a solution that uses jQuery's .map(). It still requires .toArray(), but only at the end.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.