srb633
srb633

Reputation: 813

Assign new value to item in array if it matches another item without looping

I'm needing to apply a conditional statement to every iteration of an array of object items without using for loops or any kind of loop that involves defining an index variable. Can this be achieved some how with map or filter?

Here is an example including a for loop.

const objectArray = [{key: 1}, {key: 2}, {key: 3}, {key: 4}, {key: 5}] 
let currentKey = 3

for(i=0;i<objectArray.length;i++) {
    if(objectArray[i].key === currentKey) {
       objectArray[i].key = 0
       }
}
> console.log(objectArray)
[{key: 1}, {key: 2}, {key: 0}, {key: 4}, {key: 5}]

How can I achieve this without a for loop.

Thanks

Upvotes: 0

Views: 83

Answers (5)

Bas
Bas

Reputation: 337

You could use the map function. This can transform the object and return it.

If you are not afraid of possible memory tweaks or object values that are reassigned, you can use:

const objectArray = [{key: 1}, {key: 2}, {key: 3}, {key: 4}, {key: 5}] 
const currentKey = 3
const result = objectArray.map((item)=>{
  if(item.key === currentKey)
    item.key = 0;
  return item;
});

console.log(result);

But if you don't want to risk memory tweaks, you should use:

const objectArray = [{key: 1}, {key: 2}, {key: 3}, {key: 4}, {key: 5}] 
const currentKey = 3
const result = [...objectArray.map((item)=>{
  const newItem = {...item}
  if(newItem.key === currentKey)
    newItem.key = 0;
  return newItem;
})];

console.log(result);

Upvotes: 2

MrByte
MrByte

Reputation: 41

objectArray.forEach((x) => x.key === currentKey && (x.key = 0));

Upvotes: 1

Greedo
Greedo

Reputation: 3559

A combination of map and filter will be an elegant solution:

const objectArray = [{key: 1}, {key: 2}, {key: 3}, {key: 4}, {key: 5}] 
let currentKey = 3

objectArray.filter((e) => e.key === currentKey).map((e) => e.key = 0);

console.log(objectArray)

Upvotes: 0

fedesc
fedesc

Reputation: 2610

you can use for...of

const objectArray = [{key: 1}, {key: 2}, {key: 3}, {key: 4}, {key: 5}] 
let currentKey = 3
for (el of objectArray) {
  if (el.key === currentKey) {
    el.key = 0;
  }
}
console.log(objectArray);

this doesn't require mentioning/using [i]ndex var

It invokes a custom iteration hook with statements to be executed for the value of each distinct property of the object.

Upvotes: 0

eol
eol

Reputation: 24565

If modifying the existing array is ok (i.e. inplace), you can simply do this using .find():

const objectArray = [{key: 1}, {key: 2}, {key: 3}, {key: 4}, {key: 5}]
let currentKey = 3


function replaceKey(arr, keyId, replacmentId) {
    const element = arr.find(element => element.key === keyId);
    if(element) {
        element.key = replacmentId;
    }
}

replaceKey(objectArray, currentKey, 0);
console.log(objectArray);

Upvotes: 2

Related Questions