简体   繁体   English

检查 javascript object 是否有密钥,如果确实用新密钥替换它

[英]Checking to see if javascript object has the key, if it does replace it with a new key

I want to see if my object:我想看看我的 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 .如果有,则有密钥description ,然后用information替换密钥。 How can I do it?我该怎么做?

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

if(obj.hasOwnProperty('description')) {
  obj.information = obj.description;
  delete obj.description;
}

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']);

Using the destructuring and renaming the property.使用解构和重命名属性。 This will avoid mutating the current object.这将避免改变当前的 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}));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM