Home > Blockchain >  Create an object from an array of objects using the value from one object as the key for the new obj
Create an object from an array of objects using the value from one object as the key for the new obj

Time:01-08

Newbie here trying trying to create an object from an array I am getting from Supabase when I filter on certain cities.

Here is what the data looks like coming in:

[
    {
        "weather": "sunny",
        "percentage": "31"
    },
    {
        "weather": "rain",
        "percentage": "19"
    },
    {
        "weather": "cloudy",
        "percentage": "35"
    },
    {
        "weather": "snow",
        "percentage": "15"
    }
]

How can I take that and create this?

{
    sunny: 31,
    rain: 19,
    cloudy: 35,
    snow: 15,
}

I've tried searching through multiple questions here without much luck but if this is answered elsewhere please point me to it. I am new to JS and been through tutorial hell but can't seem to get this to output what I need.

Here is the async function to get the data from Supabase:

    async function getData() {
        const { data, error } = await supabase
            .from('cities')
            .select('weather, percentage')
            .match({ city: targetCity });
        if (error) throw new Error(error.message);

The closest I have gotten is to use this:

const result = data.map(Object.values);
console.log(result);

Which gives this output but it is still arrays:

(4) [Array(2), Array(2), Array(2), Array(2)]
0: (2) ['sunny', '31']
1: (2) ['rain', '19']
2: (2) ['cloudy', '35']
3: (2) ['snow', '15']
length: 4
[[Prototype]]: Array(0)

CodePudding user response:

let input = [
    {
        "weather": "sunny",
        "percentage": "31"
    },
    {
        "weather": "rain",
        "percentage": "19"
    },
    {
        "weather": "cloudy",
        "percentage": "35"
    },
    {
        "weather": "snow",
        "percentage": "15"
    }
]

let output = {}

for (let elem of input ) {
    output[elem.weather] = elem.percentage 
}

console.log(output)

There are other ways to do it. But I am going with a simple loop as it is easier to understand. Let me know if this doesn't make sense.

  • Related