简体   繁体   中英

How can I iterate through the “keywords” array of this object to return an array of only keywords?

I can console log one keyword at a time using the forEach method as below, but can't figure out how to return an array of all keywords from the JSON at the bottom. I hope to generate the array for a bar chart of values for each keyword. The keywords will form the Y axis, and the values the X axis in a d3.js visualization.

data.forEach(function(d) {
  keywords = d.keywords
  console.log(keywords[0][0]);// "white"
});

{
        "title": "I'm Dreaming of a White Christmas",
        "artist": "Bing Crosby",
        "year": "1942",
        "sales": "50,000,000",
        "keywords": [
            [
                "white",
                6
            ],
            [
                "Christmas",
                6
            ],
            [
                "dreaming",
                4
            ],
            [
                "christmases",
                2
            ],
            [
                "merry",
                2
            ],
            [
                "write",
                2
            ],
            [
                "snow",
                2
            ],
            [
                "sleigh",
                2
            ],
            [
                "listen",
                2
            ],
            [
                "glisten",
                2
            ]
        ]
    }

I assume your data variable is your json object. If so, and if you want to get an array of all keywords (first element) you can use .map() in this way:

 var data = { "title": "I'm Dreaming of a White Christmas", "artist": "Bing Crosby", "year": "1942", "sales": "50,000,000", "keywords": [ [ "white", 6 ], [ "Christmas", 6 ], [ "dreaming", 4 ], [ "christmases", 2 ], [ "merry", 2 ], [ "write", 2 ], [ "snow", 2 ], [ "sleigh", 2 ], [ "listen", 2 ], [ "glisten", 2 ] ] }; var keywords = data.keywords.map(function(d) { return d[0]; }); console.log(keywords);

Create an empty array to store the results. Then, loop through the array of keywords, pushing the first element of each to the results array:

let results = [];
data.forEach(function(d) {
  d.keywords.forEach( function(keyword) {
    results.push( keyword[0] ); // "white"
  });
});
console.log( results );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM