0
{
    "eggs":{
        "protein":5.5,
        "count":10,
        "serving":3,
        "_comment":"Serving is per eggs"
    },
    "chicken":{
        "protein":23,
        "weight":900,
        "serving":4.5,
        "_comment":"Serving is per 100 grams" 
    },
    "kwark":{
        "protein":8.5,
        "weight":1000,
        "serving":2
    },
    "milk":{
        "protein":3.5,
        "weight":2000,
        "serving":1
    },
    "oats":{
        "protein":14,
        "weight":450,
        "serving":1
    },
    "cottageCheese":{
        "protein":19,
        "weight":200,
        "serving":1
    }
}

Json object named

const nutrition = require("./nutritionalValues.json");

Calling the json object to work at the same file.

Now what I want to do is to create variables with the same names as the keys of the JSON object. So the

Object.keys(nutrition) // ["eggs", "chicken", "kwark", "milk", "oats", "cottageCheese"]

It is possible to assign the variables right away

let {eggs, chicken, kwark, milk, oats, cottageCheese} = nutrition;

But what if I had thousands of items in the JSON file. How can I create these variables programmatically ? And/or is there a better way to manage this?

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
frank3stein
  • 706
  • 2
  • 7
  • 16
  • 1
    How does the spread operator (from title) relate to your question? – strider Nov 14 '17 at 22:32
  • 1
    "…is there a better way to manage this?" Having all your data in one object seems like a better way than a bunch of individual variables. – Mark Sep 07 '18 at 00:51
  • 2
    why do you need to create thousand of variables ? Isn't `nutrition['eggs']` suitable for you ? Destructuring object is usefull when you need some of its properties, if you need all of them I don't see the benefit of using it – Olivier Boissé Sep 07 '18 at 00:52

0 Answers0