-1

I've tried to destruct a json. This is the original:

const shoppingLists = [
{
id: 0,
name: "empty shopppinglist",
location: "",
targetDate: "",
priority: "",
isFinished: false,
items: [{
    name: ""
}]
},
{
    id: 1,
    name: "full shopppinglist",
    location: "migros",
    targetDate: "",
    priority: "1",
    isFinished: true,
    items: [{
        name: "apfel"
    }]
}}

I need now just the lists with the elements but without the items list

const { id, name, location, targetDate, priority, isFinished } = shoppingLists
res.send(shoppingLists)

But when I receive/log shoppingLists, I always get again the whole object.

I've also tried with items, ...rest but same result at the end, what am I doing wrong?

Collin
  • 339
  • 1
  • 3
  • 13
  • shoppingLists is Array – tom10271 Sep 05 '20 at 07:04
  • The point of destructuring is it's shorthand for assigning variables corresponding to either the keys or positions that exist in the object or array respectively. In your example you're destructuring an array which won't work with that syntax. Check the docs. – Phix Sep 05 '20 at 07:07
  • You can also make a `new Set` of that array and slice `items` from each object from it and `res.send(newArr)` - Instead of Destructing – Always Helping Sep 05 '20 at 07:08
  • "*I need just the lists but without the items list*". Something like this: `const newList = shoppingLists.map(({ items, ...rest }) => rest)` – adiga Sep 05 '20 at 07:15
  • 1
    I've completly forgot that this isnt' working for a list const newList = shoppingLists.map(({ items, ...rest }) => rest) solved the problem – Collin Sep 05 '20 at 07:28

1 Answers1

0

You should change your syntax since shoppingLists is an array:

const { id, name, location, targetDate, priority, isFinished } = shoppingLists[0]

Also, if you want to remove an item from an array you definitely need to use splice or if you want to remove the first element and then get its value as return then you should use shift.

const { id, name, location, targetDate, priority, isFinished } = shoppingLists.shift()
Shababb Karim
  • 3,614
  • 1
  • 22
  • 35
  • 1
    Or `const [{ id, name, location, targetDate, priority, isFinished }] = shoppingLists` – adiga Sep 05 '20 at 07:12
  • Yes [array destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) also works but OP probably wants to **remove the element** from the array and then assign it to an object. This is why I included the `shift` example code. – Shababb Karim Sep 05 '20 at 07:19