我想看看我的物体是否
{
application: "123 abc"
description: "done"
id: 672372
issueDate: "2008-07-02T00:00:00"
}
具有密钥description
(如果有),然后将其替换为information
。我该怎么办?
答案 0 :(得分:2)
const obj = {...} // => any object
if(obj.hasOwnProperty('description')) {
obj.information = obj.description;
delete obj.description;
}
答案 1 :(得分:1)
简单方法:
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']);
答案 2 :(得分:0)
使用解构和重命名财产。这样可以避免更改当前对象。
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}));