JavaScript: 如何通过解构从嵌套对象中复制几个键

JavaScript: How to copying a few keys from a nested object by destructuring

假设我有一个对象:

myObj = { 
  name: 'Luke',
  age: 12,
  height: '163cm',
  weight: '60kg',
  others: { one: '1', two: '2', three: '3'} // (Edited) Added one more key here :)
};

我想要一个没有特定键的这个对象的副本到一个新对象,输出如下:

newObj = { 
      name: 'Luke',
      age: 12,
      one: '1',
      two: '2'
    };

我见过破坏的例子,但我想知道嵌套对象是否可行。像这样的东西是否可以使用解构来实现,如果不能,那么最有效的方法是什么。

使用 destructure-like 语法实现此目的的一种方法如下:

const myObj = { 
  name: 'Luke',
  age: 12,
  height: '163cm',
  weight: '60kg',
  others: { one: '1', two: '2', three : '3'}
};


const newObj = {
  /* Copy over values from "myObj" to equivalent keys in "newObj" */
  name : myObj.name,
  age : myObj.age,

  /* Spread keys "one" and "two" of the nested "others" object into "newObj" */
  ...({one, two} = myObj.others, {one, two})
}

console.log(newObj)

对于未知深度的对象可以尝试使用递归。

  • 创建一个函数,它将一个对象和要删除的键数组作为参数。
  • 在 main 中创建一个 helper(以 1 个对象作为参数)函数并创建空对象。
  • 使用 for..in.
  • 遍历 obj 的属性
  • 检查 key 是否不存在于要删除的键数组中
    • 检查值是否为对象然后递归调用函数
    • 如果不是对象,则将其添加到结果对象中。
  • 最后return结果对象。

该代码会将未知深度的对象转换为普通对象,您还可以从嵌套对象中删除键。

const myObj = { 
  name: 'Luke',
  age: 12,
  height: '163cm',
  weight: '60kg',
  others: { one: '1', two: '2'}
};
const removed = ['height','weight','one'];

function removeKeys(obj,removed){
  const res = {};
  function helper(obj){
    for(let key in obj){
      if(!removed.includes(key)){
        if(typeof obj[key] === "object"){
          helper(obj[key]);
        }
        else res[key] = obj[key]
      }
    }
    
  }
  helper(obj)
  return res;
}

const res = removeKeys(myObj,removed);
console.log(res)

为了完整起见,iife 方法是可行的。它通过创建一个箭头函数来工作,该函数将您要保留的键作为参数。在函数体中,根据需要展开嵌套对象。

const myObj = { 
  name: 'Luke',
  age: 12,
  height: '163cm',
  weight: '60kg',
  others: { one: '1', two: '2'}
};

const newObj = (
  ({name, age, others}) => ({name, age, ...others})
)(myObj);

console.log(newObj);