1

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"
}
];
6
  • This indexes in names (0, 1, 1398083781749) are serial, with no holes? Commented Apr 21, 2014 at 12:50
  • Yes, but there are some other keys and i need just sites Commented Apr 21, 2014 at 12:53
  • You need to parse it, loop, then push into a new object and encode it to json, what language are you using? Commented Apr 21, 2014 at 12:55
  • Does the array need to be in the same order as the property "indices"? Commented Apr 21, 2014 at 12:55
  • 1
    Please note that this has nothing to do with JSON, at all. What you have is a JavaScript object and you seem to want to restructure it into an array of objects. Commented Apr 21, 2014 at 13:11

1 Answer 1

2

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_"]
        });
Sign up to request clarification or add additional context in comments.

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.