1

I am trying to take some some objects from an original object into an array variable.

console.log("news len", news["articles"].length); // this comes out to 9

for(var a in news["articles"]) {
    var results = [];
    results.push({
        title:news["articles"][a]["title"],
        subtitle: news["articles"][a]["description"],
        item_url:news["articles"][a]["title"],
        image_url:news["articles"][a]["urlToImage"],
    });
}
console.log("results len",results.length); //only contains one entry

Is there another way to accomplish this, and if not what am I doing wrong?

Using Node js if that helps any.

3
  • can you add your object news ,how does the content look in it Commented Dec 3, 2016 at 23:01
  • It looks like news["articles"] is an array, so we not just map with that? Commented Dec 3, 2016 at 23:02
  • to prevent some errors, like reinitializing empty array, i suggest to declare all variables in advance at the beginning of the code, directly after the functions - this includes variable for for, as well. Commented Dec 3, 2016 at 23:09

3 Answers 3

3

You could use map directly and return an object in the callback for a new array

var results = news.articles.map(function (a) {
        return {
            title: a.title,
            subtitle: a.description,
            item_url: a.title,
            image_url: a.urlToImage
        };
    };
Sign up to request clarification or add additional context in comments.

1 Comment

Yup, I was using the news object itself instead of news.articles. Lapse of thinking on my part, thanks!
2

The main problem is that each iteration of your loop re-sets results to an empty array:

var results=[];

If you move that statement before your loop, you will get something closer to what you want.

That said, it looks like news["articles"] already is an array, so you can probably just use Array.prototype.map?

Comments

0
var results = [];
news["articles"].map(function(val,idx){
    results.push({
       title: val["title"],
       //etc
    }
});

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.