Home > Software engineering >  How do I use a json array to create a new object with only name-value pairs with javascript?
How do I use a json array to create a new object with only name-value pairs with javascript?

Time:08-22

I want my Javascript to use this JSON file:

{
    "Campgrounds": [
        {
            "Name": "Coyote lake",
            "Address": "123 lake dr, gilroy ca 95111",
            "SiteCount": 50,
            "Funfact": "Nice lake, cows, screaming hogs"
        },
        {
            "Name": "Uvas reservoir",
            "Address": "123 lake dr, San jose ca 95111",
            "SiteCount": 50,
            "Funfact": "Nice waterfalls, trails, tall trees"
        },
        {
            "Name": "Mount Madonna",
            "Address": "123 lake dr, Santa cruz ca 95111",
            "SiteCount": 50,
            "Funfact": "Nice views, trails, tall trees"
        },
        {
            "Name": "Santa Cruz Beach",
            "Address": "1230 lake dr, Santa cruz ca 95111",
            "SiteCount": 50,
            "Funfact": "Ocean views, trails, tall trees"
        }
    ]
}

and then create a new object variable in the js which will look like this:

{
    "Campgrounds": {
        "Coyote lake" : {
            "Name": "Coyote lake",
            "Address": "123 lake dr, gilroy ca 95111",
            "SiteCount": 50,
            "Funfact": "Nice lake, cows, screaming hogs"
        },
        "Uvas reservoir" : {
            "Name": "Uvas reservoir",
            "Address": "123 lake dr, San jose ca 95111",
            "SiteCount": 50,
            "Funfact": "Nice waterfalls, trails, tall trees"
        },
        "Mount Madonna" : {
            "Name": "Mount Madonna",
            "Address": "123 lake dr, Santa cruz ca 95111",
            "SiteCount": 50,
            "Funfact": "Nice views, trails, tall trees"
        },
        "Santa Cruz Beach" : {
            "Name": "Santa Cruz Beach",
            "Address": "1230 lake dr, Santa cruz ca 95111",
            "SiteCount": 50,
            "Funfact": "Ocean views, trails, tall trees"
        }
    }
}

Essentially, I want to take the contents of the array and turn them into name-value format. Is this possible? I haven't found a way to do this.

CodePudding user response:

Assuming your object is in the data variable, you could use Array.prototype.reduce to convert it to your desired format:

const formattedData = {
    ...data,
    Campgrounds: data.Campgrounds.reduce(
        (carry, item) => ({
            ...carry,
            [item.Name]: item,
        }),
        {}
    ),
};

Does it make sense though? It doesn't look like the most elegant of the formats.

  • Related