Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

How to group select and change the values of a common property across each object in the same array?

Hi - is there a way to select and change at the same time the values inside properties common to a series of objects inside an array? For example, in the code below is there a way to access the dinner property of both the objects below, changing the value to "Tacos" at the same time?

var quotesArray = [
  {
    name: "Bob",
    dinner: "Burger"
  },
  {
    name: "Jim",
    dinner: "Pizza"
  },
];

2 Answers

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there! Not to my knowledge, no. However you can go through the list one key at a time and change all those keys to the same thing. Now it's possible that there's some trick to doing that that I'm not aware of. But I took the liberty of writing a function that does what you're asking. But there (to my knowledge) is no group select.

var quotesArray = [
  {
    name: "Bob",
    dinner: "Burger"
  },
  {
    name: "Jim",
    dinner: "Pizza"
  },
];

  function newDinner(myArr) {
    for (var key in myArr){
      myArr[key]["dinner"] = "tacos";
      console.log(myArr[key]["name"]);
      console.log(myArr[key]["dinner"]);            
    }
  }

  newDinner(quotesArray);

Hope this helps! :sparkles:

Thank you @Jennifer Nordell for the quick and helpful answer :)