1

I'm currently working on a Javascript project. I need to take specific data from a large json dataset and store it in an array for later use. This is my code so far:

publicationArray = [] = datafile["publications"]
for (p in publicationArray){
    var publication = publicationArray[p];
    publicationKeywords.push (publication.keywords);
}

As I'm sure most of you can work out, this takes all objects with the ID 'publications' from the main dataset, then loops through them, taking the keywords of each individual object and storing them in publicationKeywords (an array defined earlier in the code). The problem is that the data is stored in the format

[ [keyword1], [keyword2], [keyword3] ]

whereas I need the data in the form

[keyword1, keyword2, keyword3]

I'm very new to Javascript, so I don't really know what I'm doing wrong, or what I should search to help with it. Is what I want possible, and if so, can anyone help me with a solution?

3
  • Did you really intend to make p a global variable? If not, use var to make it local to the function where it's contained. Commented Feb 26, 2012 at 2:20
  • Just one common JS begginer pitfall: Use a regular for loop instead of for-in to iterate over arrays. Only use for-in when you need to iterate over an object's keys. Commented Feb 26, 2012 at 3:28
  • Thanks for the tips everyone. So many different ways of doing it! Commented Feb 26, 2012 at 19:03

3 Answers 3

1

Why don't you try

publicationKeywords.push (publication.keywords[0]);
Sign up to request clarification or add additional context in comments.

Comments

1
var a = [[1],[2],[3]];
var b = [];
for(var i=0,n=a.length;i<n;i++){
   b = b.concat( a[i] );
}
console.log( b );

Comments

1

If publication.keywords is an array of keywords, simply iterate it, adding each keyword to your publicationArray inside this inner loop.

var publicationArray = [] = datafile["publications"];
for (p in publicationArray){
    var publication = publicationArray[p];
    for (keyword in publication.keywords) {
        publicationKeywords.push(keyword);
    }
}

Also, you should use the vanilla for loop when iterating arrays:

for (var i = 0; i < publicationArray.length; i++) {
        var publication = publicationArray[p];
        for (var j = 0; j < publication.length, j++) {
            publicationKeywords.push(publication[j]);
        }
}

Reasoning here: https://stackoverflow.com/a/3010848/187954

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.