I am trying o get data from SWAPI to integrate with another platform using javascript. I have some saved some links inside a variable while getting data.
a = {
items: [
{ item: "https://swapi.dev/api/people/5/" },
{ item: "https://swapi.dev/api/people/68/" },
{ item: "https://swapi.dev/api/people/81/" },
],
};
From this code how do I extract the links only and save in a variable? I only need links. I tried object.values, object.keys() but couldn't find a way. The platform I am using doesn't support fetch() or $.each.
I am not quite sure how to get it done using for loop. Any assistance will be highly appreciated!
You can use a simple forEach for this task like:
const a = {
"items": [{
"item": "https://swapi.dev/api/people/5/"
}, {
"item": "https://swapi.dev/api/people/68/"
},
{
"item": "https://swapi.dev/api/people/81/"
}
]
};
a.items.forEach(el =>{
console.log(el.item);
});
Reference:
There are many different ways to achieve this, a few already suggested.
Using a for loop:
// Create an empty array to store the values
const linksArray = [];
// Loop the object items array to get its values
for (let i = 0; i < a.items.length; i++) {
// Store the values in the empty array
linksArray.push(a.items[i].item);
}
// See the results
console.log(linksArray)