简体   繁体   中英

Javascript: return the first value from arrays within an object

I am working on a javascript homework problem and am a bit stuck:

Create a function called getFirstAnimals that returns an array of all the first animals in the object. Example: ['bears','penguins',panther','flea']

I scripted the following function:

var animals = { 
mammals:['bears','lions','whales','otters'], 
birds:['penguins','ducks','swans','chickens'], 
cats:['panther','mountain lion','leopard','snow tiger'], 
insects: ['flea','mosquito','beetle','fly','grasshopper']
}

function getFirstAnimals(array) {
    var firstAnimals = [];
    for (key in array) {
        firstAnimals.push(array[key].slice(0,1))
    }
    return firstAnimals;
}

console.log(getFirstAnimals(animals));

my problem is that the output I am generating is an array of arrays made up of the first animals, [Array[1], Array[1], Array[1], Array[1]], and not the strings, ['bears','penguins',panther','flea']. Any suggestions on how to get the desired output is much appreciated.

无需推送array[key].slice(0,1)您需要推送array[key][0] ,其中[0]使您获得数组中的第一项。

You can use

firstAnimals.push(array[key][0])

for that. It gets the first element from the array

Yet another approach

 var animals = { mammals:['bears','lions','whales','otters'], birds:['penguins','ducks','swans','chickens'], cats:['panther','mountain lion','leopard','snow tiger'], insects: ['flea','mosquito','beetle','fly','grasshopper'] } function getFirstAnimals(array) { return Object.keys(array).map(v => array[v][0]); } console.log(getFirstAnimals(animals)); 

单行代码: console.log(animals[Object.keys(animals)[0]]);

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