Reputation: 487
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"]
Upvotes: 0
Views: 78
Reputation: 1561
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"]
Upvotes: 1
Reputation: 25408
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);
Upvotes: 0
Reputation: 980
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"]
Upvotes: 1