Home > Back-end >  How to append Object value with matching key in JavaScript?
How to append Object value with matching key in JavaScript?

Time:01-04

I need to understand how we can append object value with matching key in JavaScript. I have below sample object in which I need to perform this operation. The below object keep getting updated with new value in country

let obj = {
"source": "test",
"data": {
 "country": "India"
}
}

The above object keep getting updated value with country key. Let's assume this time it will be something like this

let obj = {
"source": "test",
"data": {
 "country": "USA"
}
}

My requirement is whenever object get updated, I need to append the country key value something like this way

obj = {
"source": "test",
"data": {
 "country": "India, USA"
}
}

CodePudding user response:

var AddCountry;//country updated
obj.data.country  = ", "   AddCountry;

is this what you are after? you can make it into a function like this

function update(AddCountry){
obj.data.country  = ", "   AddCountry;
}

CodePudding user response:

first object

let obj = {
 "source": "test",
 "data": {
   "country": "India"
  }
}

the updated object

const updatedObj = {
  "source": "test",
  "data": {
   "country": "USA"
  }
}

obj = {
  ...obj,
  data: {
    country: obj.data.country   ", "   updatedObj.data.country
  }
}
  • Related