2

I have the following array:

[
        {
            "name":"John Smith"
        },
        {
            "name":"Mary Kay"
        },
        {
            "name":"Peter Pan"
        },
        {
            "name":"Ben Franklin"
        }
    ];

How can I get all the first string name with lodash, like:

result = ["John", "Mary", "Peter", "Ben"]

5 Answers 5

2

Here's an alternative that makes use of lodash' flow(), that executes property() to get the property of each item in an object (e.g. name), words(), to split strings into words (array), and lastly, first() to get the first item from an array.

var result = _.map(source, _.flow(_.property('name'), _.words, _.first));

var source = [{
  "name": "John Smith"
}, {
  "name": "Mary Kay"
}, {
  "name": "Peter Pan"
}, {
  "name": "Ben Franklin"
}];

var result = _.map(source, _.flow(_.property('name'), _.words, _.first));

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

Here's another implementation of the solution above that does not use flow() and property():

var result = _.map(source, function(item) {
  return _(item.name).words().first();
});

var source = [{
  "name": "John Smith"
}, {
  "name": "Mary Kay"
}, {
  "name": "Peter Pan"
}, {
  "name": "Ben Franklin"
}];

var result = _.map(source, function(item) {
  return _(item.name).words().first();
});

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

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

Comments

2

Use JavaScript Array#map and String#split methods.

var data = [{
  "name": "John Smith"
}, {
  "name": "Mary Kay"
}, {
  "name": "Peter Pan"
}, {
  "name": "Ben Franklin"
}];

console.log(
  // iterate over the array to generate result array
  data.map(function(v) {
    // split the value by space and return first element
    return v.name.split(' ')[0];
  })
)

// with  ES6 arrow function 
console.log(
  data.map(v => v.name.split(' ')[0])
)

Comments

1
    console.log(_.map(data, function(item){
        return _.split(item.name,' ',1)[0];
    }));

Comments

0

var t = [
        {
            "name":"John Smith"
        },
        {
            "name":"Mary Kay"
        },
        {
            "name":"Peter Pan"
        },
        {
            "name":"Ben Franklin"
        }
    ];
    var result = [];
    t.forEach(function(element) {
       result.push(element.name)
    });
    console.log(result)

1 Comment

Oh yeah, only first names. My bad
0

If you like short code (using parameter destructuring to extract name):

result = _.map(data, ({name}) => _.words(name)[0]);

Comments

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.