0

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"
}
}
James
  • 371
  • 3
  • 12
  • Check out this post for some ideas. https://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically/383245#383245 – Matt Jan 04 '23 at 05:42
  • 1
    Storing a list in a string seems counter productive, the property should rather be type of array. – Teemu Jan 04 '23 at 05:48

2 Answers2

0
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;
}
yuta y
  • 144
  • 8
0

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
  }
}
Adhi Ardiansyah
  • 534
  • 2
  • 8