-2

I have an array that looks like this:

[
  {"firstName": "john", "lastName": "doe", "linkedInID":"..."},   
  {"firstName": "jane", "lastName": "doe", "linkedInID":"..."},
  {"firstName": "someone", "lastName": "Mc Donald", "linkedInID":"..."},
  ...
]

I want it to be merged to:

[
  {"Name": "john doe", "linkedInID": "..."},   
  {"Name": "jane doe", "linkedInID": "..."},
  {"Name": "someone Mc Donald", "linkedInID": "..."},
  ...
]

All new objects should have a field Name which is the concatenation of firstName and lastName.

How can I do this?

3

1 Answer 1

5

Why do you need Angular for that? One possibility is to use the native .map() javascript method in order to transform your input array:

var inputArray = [
    {"firstName":"john","lastName":" doe","linkedInID":"..."},   
    {"firstName":"jane","lastName":"doe","linkedInID":"..."},
    {"firstName":"someone","lastName":"Mc Donald","linkedInID":"..."},
    ...
];

var result = inputArray.map(function(item) {
    return {
        Name: item.firstName + ' ' + item.lastName,
        linkedInID: item.linkedInID
    };
});
Sign up to request clarification or add additional context in comments.

3 Comments

An ES6 version, please? A nice arrow function!
@Kyll inputArray.map(item => ({ Name: item.firstName + ' ' + item.lastName, linkedInID: item.linkedInID }));
There are several equivalent alternatives, e.g. using destructuring, spread syntax, and template literals: const result = inputArray.map(({ firstName, lastName, ...rest }) => ({ Name: `${firstName} ${lastName}`, ...rest }));.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.