3

I have a list which has some cities and has an empty object at the start. I need to set my empty object named best cities to an object which contains madrid like below. it should hold madrid key too in inside. I've tried to bestCity=cities.madrid but I lost the madrid key with this method. I wonder how to make this. Thank you.

cities: {
  madrid: {
    sunny: "yes",
    capital: "yes" 
  },
  london: {
    sunny: "no",
    capital: "yes"
  },
  miami: {
    sunny: "yes",
    capital: "no"
  },
  hamburg: {
    sunny: "no",
    capital: "no",
  }
}


empty object at the start:

bestCity: {}

best city should be as below.

bestCity: {
  madrid: {
    sunny: "yes",
    capital: "yes"
  }
}
1
  • 1
    You can use destructuring {bestCity : {...cities.madrid}} ? Commented Sep 5, 2019 at 17:07

4 Answers 4

3

you could use destructuring to extract madrid then creat an object with it :

const cities = {
  madrid: {
    sunny: "yes",
    capital: "yes" 
  },
  london: {
    sunny: "no",
    capital: "yes"
  },
  miami: {
    sunny: "yes",
    capital: "no"
  },
  hamburg: {
    sunny: "no",
    capital: "no",
  }
}

const { madrid } = cities ;

const bestCity = { madrid };

console.log( bestCity );

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

1 Comment

This was the exactly what I want to do. Thank you.
1

Something like this? Assuming you actually wanted to choose a good city instead of just copying a hardcoded one

const cities = { 
  madrid:  { sunny: "yes", capital: "yes" },
  london:  { sunny: "no",  capital: "yes" },
  miami:   { sunny: "yes", capital: "no"  },
  hamburg: { sunny: "no",  capital: "no", }
}

let bestCity = {};
Object.keys(cities).forEach(k => {
  const city = cities[k];
  if (city.sunny === "yes" && city.capital === "yes") bestCity[k]=city;
})
console.log(bestCity)

Comments

0

You can use cities.madrid to access the madrid object inside cities. Then, you can assign a certain variable / object value to it like so:

bestCities = {}
bestCities.madrid = cities.madrid;

Comments

0
bestCity.madrid = cities.madrid;

Comments

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.