Simba
Simba

Reputation: 275

How to check if property exsist in array of objects in JS

I've got an array with objects created dynamically. I'll use the next example:

const workers = [{
    Construction: 500,
    workers: 0
  },
  {
    Debilite: 800,
    workers: 0
  },
  {
    Marketing: 1200,
    workers: 0
  },
  {
    'Human Resources': 1350,
    workers: 0
  },
]

How to find if the property name exists and change its value? For example, if 'Construction' property exists, change its value from 500 to 800 and workers should change from 0 to 1.

Upvotes: 1

Views: 110

Answers (3)

Rounin
Rounin

Reputation: 29453

You have an array of objects.

So you need to follow two steps:

  1. Loop through the array (either using a for loop, or using forEach)
  2. On each iteration of the loop use object.hasOwnProperty(key)

In this case you can use something like:

workers.forEach((worker) => {

  if (worker.hasOwnProperty('Construction')) {
    worker['Construction'] = 800;
    worker['workers'] = 1;
  }
});

Working Example:

const workers = [{
    Construction: 500,
    workers: 0
  },
  {
    Debilite: 800,
    workers: 0
  },
  {
    Marketing: 1200,
    workers: 0
  },
  {
    'Human Resources': 1350,
    workers: 0
  },
];

workers.forEach((worker) => {

  if (worker.hasOwnProperty('Construction')) {
    worker['Construction'] = 800;
    worker['workers'] = 1;
  }
});

console.log(workers);

Upvotes: 0

Scott Marcus
Scott Marcus

Reputation: 65806

Loop over the array, examine each object, update as needed.

You do have two syntax errors with your code:

  1. There should not be a comma after the last item in an array.
  2. Human resources is not a valid object key unless it's in quotes.

const workers = [
  { Construction: 500, workers: 0 },
  { Debilite: 800, workers: 0 },
  { Marketing: 1200, workers: 0 },
  { "Human resources": 1350, workers: 0 } // <-- No comma after last array item and no spaces in key unless quoted
];

// Loop over the array
workers.forEach(function(obj){
  // Check current array item for existence of property
  if(obj.Construction){
    // Update as needed
    obj.Construction = 800;
    obj.workers = 1; 
  }
});

console.log(workers);

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386560

You could find the object and assign the new values.

function update(array, key, values) {
    Object.assign(array.find(o => key in o) || {}, values);
}

const workers = [{ Construction: 500, workers: 0 }, { Debilite: 800, workers: 0 }, { Marketing: 1200, workers: 0 }, { 'Human resources': 1350, workers: 0 }];

update(workers, 'Construction', { Construction: 800, workers: 1 });

console.log(workers);

Upvotes: 1

Related Questions