0

Using lambdas and LINQ in C#, I can create a new collection with a certain type based on a collection with a different type. For instance:

var array = new List<Foo> { new Foo { name = "John", age = "21", title = "Mr." } };
// I can then use the Select function to create a collection with a different type
var modifiedArray = array.Select(foo => new Bar { title = foo.Title });

I was wondering if there is a better way to do this in Javascript. I currently have:

var array = [{name: 'John', age: '21', title: 'Mr.'}];
var modifiedArray = [];

array.forEach(function(foo){
    modifiedArray.push({title: foo.title});
});
0

1 Answer 1

3

Yes. You can use Array.prototype.map

var modifiedArray = array.map(function(x){ 
    return {title: x.title} 
});
Sign up to request clarification or add additional context in comments.

5 Comments

That is the fastest I have EVER seen someone reply on Stack Overflow. Thank you so much!
@dimgl glad to have helped you :)
@dimgl: Note that map was added in ES5, so it's not in older browsers like IE8. It can readily be shimmed, though.
@T.J.Crowder this is for a Node.js backend script
@dimgl: Then you're fine.

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.