-1

I have an object in Javascript and it has some entries like:

{tempmin = 5,
tempmax= 10
}

I want to replace keys like:

.then(forecasts => {
                        this.foreCasts = forecasts.map(s => {
                            if (s.hasOwnProperty("tempmin")) {
                                s.tempmin = "Minimum Temperature"
                            }
                            if (s.hasOwnProperty("tempmax")) {
                                s.tempmax = "Maximum Temperature"
                            }
                        });

but I got the error : forecasts.map is not a function

I have checked this but it did not work. How can I replace these keys ?

abidinberkay
  • 1,857
  • 4
  • 36
  • 68
  • `.map()` only works on arrays. So likely `forecasts` has another type. – Sirko May 21 '20 at 20:25
  • 1
    Your object literal is incorrectly formatted. – Joel Hager May 21 '20 at 20:26
  • It's not even clear what you are trying to do here. Javascript has no list data structure. The closest thing is an array, but you've posted an object (a syntactically invalid one at that). What do you mean "replace the keys"? Do you mean create a new object with a different key but the same value? – Jared Smith May 21 '20 at 20:26
  • yes @JaredSmith it is an object sorry for saying list. As you said, I want to change these values and I can use a new object with correct values – abidinberkay May 21 '20 at 20:30
  • 1
    is `forecast` an object? Show us that data structure. – Joel Hager May 21 '20 at 20:30

1 Answers1

2

Destructure out tempmin, tempmax. Merge them back in as "Minimum..."

let forecasts = {
  tempmin: 5,
  tempmax: 10,
  blahblah: "x"
}

this.foreCasts = (({
  tempmin,
  tempmax,
  ...rest
}) => Object.assign(rest, {
  "Minimum Temperature": tempmin,
  "Maximum Temperature": tempmax
}))(forecasts);
console.log(this.foreCasts);

I prefer Object.assign, but you can also use spread syntax { ...rest, "Maximum Temperature": tempmin, "Maximum Temperature": tempmax }

user120242
  • 14,918
  • 3
  • 38
  • 52