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?

1

3 Answers 3

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

if(obj.hasOwnProperty('description')) {
  obj.information = obj.description;
  delete obj.description;
}
Sign up to request clarification or add additional context in comments.

2 Comments

what if I want to replace it with a key that has a white space in it? like "important information"?
@seyet obj['important information'] = "some new value."
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']);

Comments

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}));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.