InNeedOfKnowledge InNeedOfKnowledge - 1 month ago 10
AngularJS Question

converting an array into an array of objects with same key pairs

i have an array like this: -

["119306.jpg","149426.jpg","157715.jpg","161706.jpg","171278.jpg","172313.jpg","179934.jpg","182047.jpg","182084.jpg","182261.jpg","183351.jpg","185276.jpg","189666.jpg","190304.jpg","191798.jpg"


I need to convert this into an array of objects like this:-

var images = [
{
{
id:"119306.jpg"

},
{
id:"149426.jpg"

},
{
id:"157715.jpg"

},
{
id:"161706.jpg"
},
{
id:"171278.jpg"
},
{
id:"172313.jpg"
},
{
id:"179934.jpg"
},
{
id:"182047.jpg"
}
}


];

The reason i am trying to do this is so i can inject $stateParams and my ui-sref will have an id placeholder. Whichever image i click, after it checks the code below:-

for(var i = 0; i < response.data.length; i++) {
if($stateParams.id == response.data[i].id) {
$scope.oneimage = response.data[i].id;
}
}


Basically, all i want to do is convert that array into an array of objects but with the same key pair for each one of them. Thanks.

Answer

You could use a map function. With array being your original objects, and the resulting array being arrayOfObjs;

var arrayOfObjs = array.map(function(jpg){
  return {id:jpg};
});

Your resulting array would look like this:

[
{id:"some.jpg"},
{id:"some.jpg"},
{id:"some.jpg"}
...
]