Get values ​​by property name from an object at different levels

I have an object in the lower format, and I need to get all the values ​​from the Price property at all levels of the object.

 var o = { Id: 1, Price: 10, Attribute: { Id: 1, Price: 2, Modifier: { Id: 34, Price: 33 } } }; 

I was thinking about the LinqToJS and jquery.map() methods, but I would like to get the most general method possible. I tried this, but it only works on the first level:

 var keys = $.map(o, function(value, key) { if (key == "Price") { return value; } }); 
+7
json javascript jquery object linq
source share
3 answers

You can use a recursive function that checks the type of the property name and its type. If the name is Price , add it to the array. If it is an object, repeat this object to find the Price key. Try the following:

 function getPrices(obj, arr) { $.each(obj, function(k, v) { if (k == "Price") arr.push(v); else if (typeof(v) == 'object') getPrices(obj[k], arr); }); return arr; } var prices = getPrices(o, []); console.log(prices); // = [10, 2, 33] 

Working example

+3
source share

You can use jQuery $.map() to do this very easily:

 var o = { Id: 1, Price: 10, Attribute: { Id: 1, Price: 2, Modifier: { Id: 34, Price: 33 } } }; var res = $.map(o, function mapper(obj, key) { return key === "Price" ? obj : $.map(obj, mapper) }); document.querySelector("pre").textContent = JSON.stringify(res) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <pre></pre> 

This works because of the odd jQuery $.map function, where if you return the array from the callback, it is smoothed out as a result.

Therefore, we can recursively call $.map with the same function on any that is not the Price key, and the array returned by it will simply be omitted from the final result.

You can avoid some calls if you check typeof obj === "object" if you want.

+1
source share

You can use a for..in , recursion

 var o = { Id: 1, Price: 10, Attribute: { Id: 1, Price: 2, Modifier: { Id: 34, Price: 33 } } }; var res = []; (function re(obj) { for (var prop in obj) { if (prop === "Price") { res.push(obj[prop]) } else { re(obj[prop]) } } }(o)); console.log(res) 
0
source share

All Articles