-1

Below is the json data that'd I'd like destructure and extract just the title values.

 [{
        "id": 1,
        "title": "Python Crash Course",
        "author": "Eric Matthes",
        "quantity": 5
      },
      {
        "id": 2,
        "title": "Head-First Python",
        "author": "Paul Barry",
        "quantity": 2
      }
    ]
blackPanther
  • 181
  • 1
  • 3
  • 14
  • Is this an array of two objects? The json is not 100% valid, I guess the `[` is missing? – Narigo Jul 15 '20 at 22:52
  • My bad. You're right. I've changed the json. And the body has 15 objects. – blackPanther Jul 15 '20 at 22:54
  • Which array index and which key? Try `[{title}]` for the first or `[,{author}]` for the second. If you want all of them, you'll need to `map`. – zero298 Jul 15 '20 at 22:57

2 Answers2

1

Getting specific properties of objects inside an array does not need destructuring. This can be done with Array.prototype.map:

jsonArray.map(object => object.title);
// results in ["Python Crash Course", "Head-First Python"]

If you really want to use destructuring, you could change the function provided to map to only select the title:

jsonArray.map(({title}) => title);
// results in ["Python Crash Course", "Head-First Python"]
Narigo
  • 2,979
  • 3
  • 20
  • 31
1

If this is an array of objects and it's in the file (not as an external file) then,

const arrayObj = [
   {
    "id": 1,
    "title": "Head-First Python",
    "author": "Paul Barry",
    "quantity": 1
  },
  ...
]

const {title} = arrayObj[0]
console.log(title) //Head-First Python

That will give you the value of one object in the array. To get all the 'title' properties you could loop through the array.

arrayObj.forEach(el => {
   let {title} = el
})
gustavozapata
  • 429
  • 2
  • 7
  • 13