I'm already struggling for quite some time to extract all the labels from the object in the picture below and then store them in a single array using JavaScript...
i have been trying something like this:
for (let i = 0, len = nav_items.length; i < len; i++) {
console.log(nav_items[i].label);
}
But this only prints three different values... I need all the labels in one array together.
The ideal outcome would be an array of:
["Getting started", "Components", "For designers"]
You can create an array and push those values in it
let arr = []
for (let i = 0, len = nav_items.length; i < len; i++) {
arr.push(nav_items[i].label);
}
console.log(arr)
output
["Getting started", "Components", "For designers"]
You can map your array in to an array with only the label values like this:
var onlyLabelsArr = nav_items.map(item => item.label);
console.log(onlyLabelsArr);
will give you:
["Getting started", "Components", "For designers"]
You can get the result using for...of
loop also. Result using Array.prototype.map
and for...of
looop.
const arr = [ { label: "Getting started" }, { label: "Components" }, { label: "For designers" }, ]; // Using Array.prototype.map const result1 = arr.map(({ label }) => label); console.log(result1); // Using for...of loop const result2 = []; for (let obj of arr) { const { label } = obj; result2.push(label); } console.log(result2);
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.