Reputation: 275
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
Reputation: 29453
You have an array
of objects
.
So you need to follow two steps:
array
(either using a for
loop, or using forEach
)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
Reputation: 65806
Loop over the array, examine each object, update as needed.
You do have two syntax errors with your code:
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
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