0

I'm trying to target the specific items in each object within an array, in order to use them as variables elsewhere. How can I create variables using each of the items? Something like var thisThing = things.title; ?

things: [
    {title: "The title for this thing", url: "https://stackoverflow.com"},
    {title: "The title for this thing", url: "https://stackoverflow.com"},
    {title: "The title for this thing", url: "https://stackoverflow.com"},
    {title: "The title for this thing", url: "https://stackoverflow.com"}
    ]
yerme
  • 810
  • 5
  • 15
  • 2
    You can get the first thing's title via `things[0].title`, the second one via `things[1].title`, etc. See the linked question's answers for details. You can also [loop through](https://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript/9329476#9329476) the array. – T.J. Crowder Aug 20 '19 at 15:21

1 Answers1

1

One approach you could use to achieve that is using ES6 object destructuring. Just wrap your variable name(s) in curly braces such that they match the name of the object properties. For example:

const things = [{
    title: "The title for this thing 1",
    url: "https://stackoverflow.com"
  },
  {
    title: "The title for this thing 2",
    url: "https://stackoverflow.com"
  },
  {
    title: "The title for this thing 3 ",
    url: "https://stackoverflow.com"
  },
  {
    title: "The title for this thing 4",
    url: "https://stackoverflow.com"
  }
];


things.forEach(thing => {
  const {title, url} = thing;
  console.log(title);
  console.log(url);
  console.log('');
})

If, you're coding to an earlier spec than ES6, you can simply use the index to access the element in the array and dot notation to obtain the property value (as TJ mentioned in his comment):

console.log(things[0].title)

Tom O.
  • 5,730
  • 2
  • 21
  • 35