0

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

1

2 Answers 2

1
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.

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

2 Comments

OP want to do this in 1 or 2 lines but you have 3 :-D
@Grundy you can put it all on 1 line - but I prefer to use 3 lines for readability.
0
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;}));

5 Comments

Ignored call to 'alert()'. The document is sandboxed, and the 'allow-modals' keyword is not set.
Where do you get this message ? On chromium 45.0 the alert is shown
Chrome 46.0.2490.80 m
Works for me. I get the alert. Running Chrome version 46.0.2490.80 m.

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.