简体   繁体   中英

Projecting javascript object members into an array

I have an object as follows:

asset: {
    images []
}

Images look like this:

image {
    width,
    height,
    fileName
}

I need to project all of the image filenames into an array. The obvious implementation is the following:

var fileNames = [];
var i;
for (i = 0; i < asset.images.length; i++) {
    fileNames.push(asset.images[i].fileName);
}

Does anybody know of a fancy way to do this in 1 or 2 lines? You can use jQuery or angularJs

var fileNames = asset.images.map(function(i) {
  return i.fileName;
});

That is the quickest way to run a set of instructions over each element of an array.

asset.images.map(function(i) {return i.fileName;};);

 var asset = {}; asset.images = []; asset.images.push({fileName: "test1"}); asset.images.push({fileName: "test2"}); asset.images.push({fileName: "test3"}); asset.images.push({fileName: "test4"}); alert(asset.images.map(function(i) {return i.fileName;})); 

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