Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
70
rated 0 times [  72] [ 2]  / answers: 1 / hits: 22678  / 10 Years ago, fri, january 9, 2015, 12:00:00

Let say We have the following json object:



[{a1 : a1Val, a2 : a2Val, a3 : a3Val}, 
{b1 : b1Val, b2 : b2Val, b3 : b3Val},

....

{z1 : z1Val, z2 : z2Val, z3 : z3Val}]


How can we retrieve from this object array of only X2 key value pairs.



meaning, the following result:



 [ {a2 : a2Val}, {b2 : b2Val}, ... ,{ z2 : z2Val}] 


within the best performance.



The key does not have to contains number.



What I need here is a function that will recieve parameter - i
and return an array of all the i-th objects in the original json object



So for example if we look at the above json object
and we invoke the method we 2 the method will return



 [ {a2 : a2Val}, {b2 : b2Val}, ... ,{ z2 : z2Val}] 


Hope it's clear enough.


More From » arrays

 Answers
43

You could use Array.map here



var arr = oldArr.map(function(obj){
var key = Object.keys(obj).sort()[1], rtn = {};
return rtn[key] = obj[key], rtn;
});


What you're doing is taking the second key and then returning a new Object with that key and value.


[#68265] Wednesday, January 7, 2015, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kenyonmasonc

Total Points: 44
Total Questions: 117
Total Answers: 116

Location: Morocco
Member since Fri, May 22, 2020
4 Years ago
;