Search code examples
lodashtransformation

Lodash map to array of objects


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,...).


Solution

  • 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>