Eyad Farra
Eyad Farra

Reputation: 4423

How to restructure object to array of objects?

I have this object

var data = {
         _id : 131233442543,
         SocialMedia_0__Name_: "facebook",
         SocialMedia_0__URL_: "http://facebook.com/test",
         SocialMedia_1__Name_: "twitter",
         SocialMedia_1__URL_: "http://twitter.com/test",
         SocialMedia_1398083781749__Name_: "linkedin",
         SocialMedia_1398083781749__URL_: "http://linkedin.com/test"
        };

And I need to restructure the object to be like this:

justSites = [
{
name : "facebook",
url : "http://facebook.com/test"
},
{
name : "twitter",
url : "http://twitter.com/test"
},
{
name : "linkedin",
url : "http://linkedin.com/test"
}
];

Upvotes: 1

Views: 316

Answers (1)

Bergi
Bergi

Reputation: 665364

This should do it:

var justSites = [], m;
for (var p in data)
    if (m = p.match(/SocialMedia_(\d+)__Name_/))
        justSites.push({
            name: data[p],
            url: data["SocialMedia_"+m[1]+"__URL_"]
        });

Upvotes: 2

Related Questions