1

i'm trying to filter an array and get the phone numbers from an address book using lodash, the structure is something like

var obj = {
  'contacts': [{
    'id': 1,
    'displayName': 'John Doe',
    'phonenumbers': [{
      'id': '1',
      'type': 'mobile',
      "pref":false,
      'value': '555-555'
    }, {
      'id': '2',
      'type': 'mobile',
      "pref":false,
      'value': '555-554'
    }]
  }, {
    'id': 2,
    'displayName': 'Jane Doe',
    'phonenumbers': [{
      'id': '1',
      'type': 'mobile',
      "pref":false,
      'value': '555-557'
    }]
  }]
}

i can try to reach the phone numbers with something like:

        lodash.map(
                contacts,
                function(person) {
                    return { id: person.id,
                        displayName: person.displayName,
                        phoneNumbers: [
                            {
                                number: person.phoneNumbers[0].value,
                                type: person.phoneNumbers[0].type}
                        ],
                        photos: person.photos };
                }
            );

but when i want to get the 2 and third with person.phoneNumbers[1].value, i get errors when there is no second phone number, is there a way to get them without specifying the position in the array? the output should be a new array with the id of the contact and the phone numbers and type.

var ouptput= {
  'contacts': [{
    'id': 1,
    'phonenumbers': [{
      'type': 'mobile',
      'value': '555-555'
    }, {
      'type': 'mobile',
      'value': '555-554'
    }]
  }, {
    'id': 2,
    'phonenumbers': [{
      'type': 'mobile',
      'value': '555-557'
    }]
  }]
}

1 Answer 1

3

You don't need lodash for this anymore if you're using es6.

contacts.map( ({ id, phonenumbers }) => 
  ({ id, phonenumbers: phonenumbers.map( ({ value, type }) => ({ value, type }) ) })
);

And you get the exact output you wanted.

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

3 Comments

You don't even need to use ES6 to do this. Although it does make the code shorter and better.
True, it's mainly a syntax thing. Also: IE > 8.
@samislimani yeah for simple stuff like this you tend to not really need lodash that often.

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.