0

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!

Phil
  • 157,677
  • 23
  • 242
  • 245
Tom
  • 3
  • 4

2 Answers2

0

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:

Simone Rossaini
  • 8,115
  • 1
  • 13
  • 34
0

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)
Ricardo Sanchez
  • 4,935
  • 11
  • 56
  • 86