0

I want to see if my object:

{
application: "123 abc"
description: "done"
id: 672372
issueDate: "2008-07-02T00:00:00"
}

has the key description if it does then replace the key with information. How can I do it?

seyet
  • 1,080
  • 4
  • 23
  • 42

3 Answers3

2
const obj = {...} // => any object

if(obj.hasOwnProperty('description')) {
  obj.information = obj.description;
  delete obj.description;
}
julianobrasil
  • 8,954
  • 2
  • 33
  • 55
1

Simple way:

var obj = {
  application: "123 abc",
  description: "done",
  id: 672372,
  issueDate: "2008-07-02T00:00:00"
}
console.log('before' + obj['application']);
if(obj['application']) {
  obj['application'] = 'new value';
}

console.log('after' + obj['application']);
Susheel Singh
  • 3,824
  • 5
  • 31
  • 66
0

Using the destructuring and renaming the property. This will avoid mutating the current object.

obj = {
  application: "123 abc",
  description: "done",
  id: 672372,
  issueDate: "2008-07-02T00:00:00",
};

const update = ({ description: information, ...rest }) =>
  Object.assign(rest, information ? { information } : {});

console.log(update(obj));

console.log(update({id: 2}));
Siva K V
  • 10,561
  • 2
  • 16
  • 29