0

What is the best way to transform a key : value object to values only array in Javascript? I'm trying to perform a mongoose query using $in. As far as I know, I need to transform this:

[ { "key": "54ce3bef2d1ce6a82c90ccc3" }, { "key": "54d290a23eff5da01d05fe53" } ]

to this:

[ "54ce3bef2d1ce6a82c90ccc3", "54d290a23eff5da01d05fe53" ]

Should I loop through the first one and then create the second one in the loop? Or should I use some map function (eg. $.map())? Is it wise to perform this operation client side or should I do all the work server side? Source object can grow as much as a few thousand pairs.

2 Answers 2

1

You can do this quickly for known keys with Array.prototype.map

var arr = [{"key": "54ce3bef2d1ce6a82c90ccc3"}, {"key": "54d290a23eff5da01d05fe53"}];

arr = arr.map(function (e) {return e.key;});
// ["54ce3bef2d1ce6a82c90ccc3", "54d290a23eff5da01d05fe53"]

If the key is unknown but you know there is only one per item, combine with a for..in

arr = arr.map(function (e) {
    var key;
    for (key in e) // may also want to Object.prototype.hasOwnProperty here
        return e[key];
});
// ["54ce3bef2d1ce6a82c90ccc3", "54d290a23eff5da01d05fe53"]
Sign up to request clarification or add additional context in comments.

Comments

1

Tough call, but my first inclination would be to do a loop, but do you have to worry about duplicates? Below does not account for that...

var arrayToStoreValues = [];
$.each(queryReturnSet,function(i,e){
     arrayToStoreValues[i] = e.key;
});

1 Comment

No duplicates. I decided to use arr.map approach. But still not sure which is better from performance perspective. Also not sure about doing this in an angular controller or in the node side is better.

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.