Tuesday, May 21, 2024
 Popular · Latest · Hot · Upcoming
179
rated 0 times [  186] [ 7]  / answers: 1 / hits: 23236  / 9 Years ago, thu, july 30, 2015, 12:00:00

I need to find the fastest way to remove all $meta properties and their values from an object, for example:



{
part_one: {
name: My Name,
something: 123,
$meta: {
test: test123
}
},
part_two: [
{
name: name,
dob: dob,
$meta: {
something: else,
and: more
}
},
{
name: name,
dob: dob
}
],
$meta: {
one: 1,
two: 2
}
}


Should become the following given that the $meta property could be at any point in the object so some form of recursion will probably be needed.



{
part_one: {
name: My Name,
something: 123
},
part_two: [
{
name: name,
dob: dob
},
{
name: name,
dob: dob
}
]
}


Any help or advice would be greatly appreciated!



Thank you!


More From » object

 Answers
0

A simple self-calling function can do it.



function removeMeta(obj) {
for(prop in obj) {
if (prop === '$meta')
delete obj[prop];
else if (typeof obj[prop] === 'object')
removeMeta(obj[prop]);
}
}




var myObj = {
part_one: {
name: My Name,
something: 123,
$meta: {
test: test123
}
},
part_two: [
{
name: name,
dob: dob,
$meta: {
something: else,
and: more
}
},
{
name: name,
dob: dob
}
],
$meta: {
one: 1,
two: 2
}
}

function removeMeta(obj) {
for(prop in obj) {
if (prop === '$meta')
delete obj[prop];
else if (typeof obj[prop] === 'object')
removeMeta(obj[prop]);
}
}

removeMeta(myObj);

console.log(myObj);




[#65600] Wednesday, July 29, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
myrap

Total Points: 407
Total Questions: 105
Total Answers: 109

Location: Cambodia
Member since Thu, Oct 7, 2021
3 Years ago
myrap questions
Tue, Feb 8, 22, 00:00, 2 Years ago
Wed, Jan 15, 20, 00:00, 4 Years ago
Thu, Oct 24, 19, 00:00, 5 Years ago
Thu, Oct 3, 19, 00:00, 5 Years ago
Mon, Aug 12, 19, 00:00, 5 Years ago
;