Mac_W
Mac_W

Reputation: 2987

Looping / iterating through an array of objects to return and array of strings - Javascript

I've got an array of objects looking like this:

[{"key":"aaa","value":true},{"key":"bbb","value":false},{"key":"ccc","value":true}]

How can I iterate through it to get an array of?

["aaa", "bbb", "ccc"]

I am using node.js and this is the code. When I loop through it I get returned only the first "aaa" and I want to get a variable being an array of 3 objects?

router.get('/', function(req, res, next) {
    db.executeSql("SELECT this FROM that", function (data, err) {
        if (err) {       
            res.json(err);
        } 
        else {
            for (var i in data) {
                    for (var i=0; i < data.length; i++) {
                        var obj = data[i];
                        for (var property in obj) {
                            var a = (obj[property]);
                                res.json(a);
                                }
                    }
                }
            }   
        }   
        res.end();
    });
  });

If you could point me to the right direction or show me some examples, thanks!

Upvotes: 0

Views: 99

Answers (2)

Ramya
Ramya

Reputation: 1

var newArr = [];
var data = [{"key":"aaa","value":true},{"key":"bbb","value":false},{"key":"ccc","value":true}];
for(var i=0;i<data.length;i++){
    newArr.push(data[i].key);
}
return newArr;

Upvotes: 0

intentionally-left-nil
intentionally-left-nil

Reputation: 8284

var input = [{"key":"aaa","value":true},{"key":"bbb","value":false},{"key":"ccc","value":true}];

var output = input.map(function(datum){
    return datum.key;
});

returns an array of ["aaa", "bbb", "ccc"]

Upvotes: 5

Related Questions