0

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.

7
  • 5
    Your result isn't a valid array. Do you want an object ({"a2":"a2Val","b2":"b2Val"...}); an array of objects ([{"a2":"a2Val"},{"b2":"b2Val"}...]) or something else? Commented Jan 9, 2015 at 14:27
  • is this the actual format of your data? will you always have a through z? Commented Jan 9, 2015 at 14:27
  • 1
    I expect you mean you want a dictionary with only the pairs specified? The problem is that dictionaries are not ordered. Do the keys actually contain numbers? Commented Jan 9, 2015 at 14:29
  • @Paul Roub , I want an array of objects.. I'll update the question Commented Jan 9, 2015 at 14:33
  • @SanjayManohar, The keys does not have to contains number.. Commented Jan 9, 2015 at 14:36

7 Answers 7

9

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Had a same thought as you, but your solution is even fancier. Damn, I like how you used the , in your return statement!
@Qwerty ah! You're the first person who has appreciated the usage of comma operator. Thanks for that :)
@AmitJoki , Thanks, this is the most elegant way I saw for doing that. I'll use your way!
@johnSmith glad to have helped you :)
3
var initialArr = [
                  {"a1" : "a1Val", "a2" : "a2Val", "a3" : "a3Val"}, 
                  {"b1" : "b1Val", "b2" : "b2Val", "b3" : "b3Val"},
                  {"z1" : "z1Val", "z2" : "z2Val", "z3" : "z3Val"}
                 ];

var resArr = initialArr.map(function(x){
    return x[Object.keys(x)[1]];
});

jsFiddle Demo

Here in this resArr, I am mapping it to initialArr[ ], to generate an array out of it called resArr and the each element initialArr is represented as 'x' in this x is an object now inorde to get the 2nd element of the object x[1] so here, 1 represents the second element as index starts from 0,1 ,,,so we need to get the keys of that object by Object.keys(x)[1]...hence value would be x[Object.keys(x)[1]].

2 Comments

pls add a more detailed explanation - stackoverflow.com/help/how-to-answer
fine but directly on your answer not on the comments.
1

Just a really fancy way to do exactly what you asked. Applicable to anything after little tweaking

var json   = '[{"a1" : "a1Val", "a2" : "a2Val", "a3" : "a3Val"},{"b1" : "b1Val", "b2" : "b2Val", "b3" : "b3Val"},{"z1" : "z1Val", "z2" : "z2Val", "z3" : "z3Val"}]',
    parsed = JSON.parse(json),
    index  = 2, // here goes your value

    result = parsed.map(function(obj){
               var key = Object.keys(obj)[0][0]+index,
                   retDict = {};
               return retDict[key] = obj[key], retDict;
             });

Run this in a console and see.

Comments

1

You will probably find that it is more efficient to do this when parsing your JSON string by using a reviver function. Something like this.

var json = '[{"a1" : "a1Val", "a2" : "a2Val", "a3" : "a3Val"},{"b1" : "b1Val", "b2" : "b2Val", "b3" : "b3Val"},{"z1" : "z1Val", "z2" : "z2Val", "z3" : "z3Val"}]',
    data = JSON.parse(json, function (key, value) {
        if (key !== "" && typeof value === 'object') {
            Object.keys(value).forEach(function (name) {
                if (name.slice(-1) !== '2') {
                    delete value[name];
                }
            });
        }

        return value;
    });

document.body.appendChild(document.createTextNode(JSON.stringify(data)));

1 Comment

I'd like thie answer as well!
0

Do a forEach loop on the array. Then for each value get the key with a regular expression. (Loop through object get value using regex key matches Javascript). I won't give you the full code because it is easy to implement and it is a good learning experience.

Comments

0

Convert to array, map the keys, filter results, concat it all, etc. This should work for you:

var result = arr
    .map(function (obj) { 
        return Object.keys(obj).map(function (key) {
            var result = {};
            result[key] = obj[key];

            if (key.substring(1) === "2") {
                return result;
            }
        });
    })
    .reduce(function (x, y) { return x.concat(y); }, [])
    .filter(function (obj) { return obj });

See working fiddle.

Comments

0

What about this:

var collection, key, obj, objArr, _i, _len, _tmp;

collection = [
  {
    "a1": "a1Val",
    "a2": "a2Val",
    "a3": "a3Val"
  }, {
    "b1": "b1Val",
    "b2": "b2Val",
    "b3": "b3Val"
  }
];

objArr = [];

for (_i = 0, _len = collection.length; _i < _len; _i++) {
  obj = collection[_i];
  for (key in obj) {
    _tmp = {};
    _tmp[key] = obj[key];
    objArr.push(_tmp);
  }
}

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.