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?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • 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. – ThiefMaster Feb 26 '12 at 02: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. – hugomg Feb 26 '12 at 03:28
  • Thanks for the tips everyone. So many different ways of doing it! – Jamie Cruickshank Feb 26 '12 at 19:03

3 Answers3

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

Community
  • 1
  • 1
Michael Robinson
  • 29,278
  • 12
  • 104
  • 130
1

Why don't you try

publicationKeywords.push (publication.keywords[0]);
user1227804
  • 390
  • 1
  • 5
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 );
epascarello
  • 204,599
  • 20
  • 195
  • 236