【问题标题】:Checking to see if javascript object has the key, if it does replace it with a new key检查javascript对象是否有密钥,如果它确实用新密钥替换它
【发布时间】:2020-07-22 02:27:11
【问题描述】:

我想看看我的对象:

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

如果有密钥description,则将密钥替换为information。我该怎么做?

【问题讨论】:

标签: javascript arrays object key


【解决方案1】:
const obj = {...} // => any object

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

【讨论】:

  • 如果我想用其中有空格的键替换它怎么办?比如“重要信息”?
  • @seyet obj['important information'] = "some new value."
【解决方案2】:

简单的方法:

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

【讨论】:

    【解决方案3】:

    使用解构和重命名属性。这将避免改变当前对象。

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

    【讨论】:

      猜你喜欢
      • 2018-06-09
      • 1970-01-01
      • 1970-01-01
      • 2012-11-24
      • 2011-05-24
      • 1970-01-01
      • 1970-01-01
      • 2021-11-20
      • 1970-01-01
      相关资源
      最近更新 更多