0

I have an array of objects as follows:

var lanes = [
{
 "name" : "Breakfast Special",
 "className" : "breakfast-special",
 "sales" : 200,
 "redemptions" : 137
},
{
 "name" : "Free Danish",
 "className" : "free-danish",
 "sales" : 300,
 "redemptions" : 237
},
{
 "name" : "Half Price Coffee",
 "className" : "half-price-coffee",
 "sales" : 240,
 "redemptions" : 37
}];

I want to create an array that contains only numerical values stored for 'redemptions'. I can access values as:

lanes[0].redemptions;

By going through each object using a loop, but I am looking for some efficient way to do that.

I tried this using map function as follows:

var arrayRedemptions = lanes.map(function () {return this.redemptions});

But it's not working. Any help would be appreciated.

1
  • Those are object literals, not "JSON objects". It is a fairly common misconception. Commented Aug 30, 2015 at 7:05

3 Answers 3

2

You are quite close.

use

var arrayRedemptions = lanes.map(function(obj) {
    return obj.redemptions
});
Sign up to request clarification or add additional context in comments.

5 Comments

Got it, the error was, I had some empty objects in the array. Fixed it like this: var arrayRedemptions = lanes.map(function(obj) { if (obj) { return obj.redemptions; } else { return -1; } });
you just check: return obj && obj.redemptions
@SheraliTurdiyev Sorry didn't get your comment. What does that mean?
no problem @user3130733. if obj equals undefined or null map returns it. It is for your prev comment(which is that: Got it, the error was). Also, i edited my answer
Perfect, Thanks!! @SheraliTurdiyev
2

yeah. inside of map you can use these params(each item, index, array)

var arrayRedemptions = lanes.map(function (item, index, array) {
    return item ? item.redemptions : -1;
});

Comments

0

Just after adding extra check especially while working with Auto Generated Content:

var arrayRedemptions = array.map(function(obj) {
    if (obj) 
        return obj.redemptions;
    else
        return -1;
}); 

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.