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"
}
];
Felix Kling
820k181 gold badges1.1k silver badges1.2k bronze badges
asked Apr 21, 2014 at 12:44
Eyad Farra
4,4231 gold badge26 silver badges27 bronze badges
-
This indexes in names (0, 1, 1398083781749) are serial, with no holes?Tommi– Tommi2014年04月21日 12:50:31 +00:00Commented Apr 21, 2014 at 12:50
-
Yes, but there are some other keys and i need just sitesEyad Farra– Eyad Farra2014年04月21日 12:53:49 +00:00Commented 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?Yazan Malkawi– Yazan Malkawi2014年04月21日 12:55:36 +00:00Commented Apr 21, 2014 at 12:55
-
Does the array need to be in the same order as the property "indices"?Bergi– Bergi2014年04月21日 12:55:53 +00:00Commented Apr 21, 2014 at 12:55
-
1Please 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.Felix Kling– Felix Kling2014年04月21日 13:11:40 +00:00Commented Apr 21, 2014 at 13:11
1 Answer 1
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_"]
});
answered Apr 21, 2014 at 12:58
Bergi
671k162 gold badges1k silver badges1.5k bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js