javascript 删除对象内的键值对

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 删除对象内的键值对相关的知识,希望对你有一定的参考价值。

const user = {name: 'Shivek Khurana', age: 23, password: 'SantaCl@use'};
const userWithoutPassword = Object.keys(user)
  .filter(key => key !== 'password')
  .map(key => ({[key]: user[key]}))
  .reduce((accumulator, current) => 
    ({...accumulator, ...current}),
    {}
  )
;
// userWithoutPassword becomes {name: 'Shivek Khurana', age: 23}

//cleaner way ?
const user = {name: 'Shivek Khurana', age: 23, password: 'SantaCl@use'};
const userWithoutPassword = (({name, age}) => ({name, age}))(user);

//better way
const user = {name: 'Shivek Khurana', age: 23, password: 'SantaCl@use'};
const userWithoutPassword = Object.keys(user)
  .reduce((acc, key) => key === ‘password’ ? 
    acc : ({ …acc, [key]: user[key] }), 
    {}
  );
  
//better way for collection of keys
const user = {name: 'Shivek Khurana', age: 23, password: 'SantaCl@use'};
const userWithoutPasswordAndAge = Object.keys(user)
  .reduce((acc, key) => ['password', 'age'].indexOf(key) > -1 ? 
    acc : ({ …acc, [key]: user[key] }), 
    {}
  );

以上是关于javascript 删除对象内的键值对的主要内容,如果未能解决你的问题,请参考以下文章

localStorage

javascript点语法与中括号语法

观察 NSMutableSet 的键值对

从 JavaScript 中的键值对数组中求和值

JavaScript:检查对象数组中是不是存在重复的键值并删除所有但最近添加的具有该键值的对象

使用Javascript拆分由“&”分隔的键值对响应[重复]