简体   繁体   中英

Creating an object array with a different type from an existing object array in Javascript

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});
});

Yes. You can use Array.prototype.map

var modifiedArray = array.map(function(x){ 
    return {title: x.title} 
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM