Home > database >  Replace attribute value in a Javascript Object
Replace attribute value in a Javascript Object

Time:05-20

I have an array in this format:

var arr = [{id: 1, age: 25, money: 2500},{id: 10, age: 10, money: 100},{id: 115, age: 80, money: 1350}]

What I want is to replace every id value with null. My first idea would have been to build a regex im combination with a for loop. But is there maybe a more efficient way to do this?

CodePudding user response:

See map method.

const source = [{id: 1, age: 25, money: 2500},{id: 10, age: 10, money: 100},{id: 115, age: 80, money: 1350}];

const destination = source.map((el) => ({ ...el, id: null }));

// For demo purpose
console.log(destination);

CodePudding user response:

var arr = [{id: 1, age: 25, money: 2500},{id: 10, age: 10, money: 100},{id: 115, age: 80, money: 1350}] 

arr.forEach(item => {
  Object.keys(item).forEach(function(key) {
    if(key ==='id') {
      item[key] = null;
    }

  });
})


console.log(arr)

CodePudding user response:

Read through documentation :

The RegExp object is used for matching text with a pattern.

Here, working with regex would be really unefficient since you work with objects


There are multiple ways of doing what you want :

You can use a for i loop to loop through your items

const arr = [{id: 1, age: 25, money: 2500},{id: 10, age: 10, money: 100},{id: 115, age: 80, money: 1350}]

for (let i=0; i<arr.length;i  ){
  arr[i].id = null
}

console.log(arr)

Or with the Array#forEach method on arrays :

const arr = [{id: 1, age: 25, money: 2500},{id: 10, age: 10, money: 100},{id: 115, age: 80, money: 1350}]

arr.forEach(item => {
  item.id = null
}) 

console.log(arr)


You could also have used Array#Map

const arr = [{id: 1, age: 25, money: 2500},{id: 10, age: 10, money: 100},{id: 115, age: 80, money: 1350}]

const arrWithoutIds = arr.map(item => {
  item.id = null
  return item
})

console.log(arrWithoutIds)

  • Related