2

How can I get all keys with values of an array of objects as an array?

For example I want to have all the src keys as array for an assetloader:

images = [
    {"name":"an image","src":"http://source.png"},
    {"name":"an image2","src":"http://source2.png"},
    {"name":"an image3","src":"http://source3.png"}
];

//the solution code here..

console.log(solution); 

// Output:
// ["http://source.png", "http://source.png2","http://source3.png"]

I can loop through the images array and push all the 'src' tags into the solution var, but I think this is not an good practise in terms of performance.

Also I can't use the original image.src tag, the assetloader is from an framework and accepts only an array with sources.

8
  • 2
    Why do you think that? And what kind of code do you expect a solution to show if not exactly what you describe? Commented Jul 14, 2014 at 13:20
  • Lets say I have an array of 10,000 images. I think that will draw performance to convert all the images to an array of images.src Commented Jul 14, 2014 at 13:21
  • 1
    @Ismail: Have you profiled it? No algorithm here is going to do better than O(n) because you have to hit every entry of images at some point. Commented Jul 14, 2014 at 13:24
  • 1
    Can't you just use the original images array instead of (partially) duplicating it? This should save the most of the overhead you worry about. Commented Jul 14, 2014 at 13:26
  • 1
    So 'scratch when itch': build the sources array as suggested here; there might be no actual performance issue as long as you have so few images that the assetloader can easily load them... ;-) Commented Jul 14, 2014 at 13:34

2 Answers 2

4

you can use native map function for this.

var solution = images.map(function (img) {
    return img.src;
})
console.log(solution);
Sign up to request clarification or add additional context in comments.

Comments

0

One liner for Mritunjay's answer

images.map((i) => i.src)

Comments

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.