0

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!

2 Answers 2

5
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"]

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

3 Comments

after adding this code to else statement var output = data.map(function(datum){ return datum.key; }); res.json(output); it return [null,null]
I see that you have found out your issue below. In general, it is possible to run my above sample through your favorite javascript interpreter and see that output in this case does in fact equal ["aaa", "bbb", "ccc"]. So, there are a few possibilities here: Perhaps the inputs are wrong and they don't match. Perhaps how you are using the code snippet doesn't work. Or perhaps the caller is not getting the results properly. Adding debugging statements (console.log or otherwise) should generally help you further narrow down your issue.
you're right I've used a wrong query statement. Now I can see that map function is not mapping it just returns the whole array. I tested it somewhere else and it worked indeed. Do you think it can be related to mssql module which I am using or is it my mistake somewhere?
0
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;

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.