-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 ?

5
  • .map() only works on arrays. So likely forecasts has another type. Commented May 21, 2020 at 20:25
  • 1
    Your object literal is incorrectly formatted. Commented May 21, 2020 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? Commented May 21, 2020 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 Commented May 21, 2020 at 20:30
  • 1
    is forecast an object? Show us that data structure. Commented May 21, 2020 at 20:30

1 Answer 1

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 }

Sign up to request clarification or add additional context in comments.

1 Comment

forgot a starting parens

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.