Home > Enterprise >  change object property value by other object property value Typescript [duplicate]
change object property value by other object property value Typescript [duplicate]

Time:10-01

Hello I want to change a property value of an object by another property value of another object

I have two arrays:

let arr1 = [{id:1, name:'test user', imageURL:''}, {id:1, name:'test user', imageURL:''}, {id:1, name:'test user 3', imageURL:''}];
let arr2 = [{id:1, name:'test user', imageURL:'abcdefghijklmnop'}];

How can I set the value imageURL from arr2 in arr1 imageURL by id in Typescript?

pseudocode: If id in arr2 matches with id in arr1 set arr1.imageURL = arr2.imageURL

Info: I am not allowed to replace the entire object. Only to change the imageURL value

CodePudding user response:

Assuming arr2 has only one value,

this.arr1.forEach((item) => {
  if(item.id == this.arr2[0].id) {
    item[imageUrl] = this.arr2[0].imageUrl
  }
})

If arr2 has multiple values, you can use forEach in the same too

CodePudding user response:

let arr1 = [{id:1, name:'test user', imageURL:''}, {id:1, name:'test user', imageURL:''}, {id:1, name:'test user 3', imageURL:''}];
let arr2 = [{id:1, name:'test user', imageURL:'abcdefghijklmnop'}];

function setUrl(arr1, arr2, id) {
   let obj = arr2.find(prop => prop.id == id)
   if(!obj) return null;
   let response = arr1.map(prop => {
      if(prop.id === id) {
         prop.imageURL = obj.imageURL
      }
      return prop
   })
   return response
}

let result = setUrl(arr1, arr2, 1)

console.log(result)

  • Related