【问题标题】:JavaScript: How to copying a few keys from a nested object by destructuringJavaScript:如何通过解构从嵌套对象中复制几个键
【发布时间】:2019-09-25 18:00:01
【问题描述】:

假设我有一个对象:

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

我见过破坏的例子,但我想知道嵌套对象是否可行。像这样使用解构是否可行,或者如果不是最有效的方法。

【问题讨论】:

  • 对于任何深度级别或某些特定的已知结构,您是否需要这个?
  • 到目前为止,已知的结构应该没问题。我已经更新了我的问题。 :)
  • 效率如何?

标签: javascript ecmascript-6 destructuring


【解决方案1】:

使用类似解构的语法实现此目的的一种方法是:

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)

【讨论】:

  • 感谢您的回复。如果我只需要嵌套对象中的键“一”怎么办。这可能吗?
  • 我已经更新了这个问题。你能看看那里吗:)
  • @Outlooker 在这种情况下,也许您可​​以将...myObj.others 替换为...({one} = myObj.others, {one})
  • @Outlooker 抱歉 - 刚刚更新了您更新问题的答案,有帮助吗?
  • @DacreDenny 绝对是。感谢您的所有帮助:)
【解决方案2】:

为了完整起见,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);

【讨论】:

  • 感谢您的回复。如果我只需要嵌套对象中的键“一”怎么办。这可能吗?我已经更新了问题。
  • 你可以使用Object.assign({}, {name, age}, {one: others.one})作为函数体。但是,听起来您正在寻找一个通用功能,该功能将需要保留一组键并递归复制所有内容(可能带有展平)?你能进一步说明你的要求吗?否则,就是打地鼠。
【解决方案3】:

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

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

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

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)

【讨论】:

  • 感谢您的回复。如果我只需要已知深度的嵌套对象中的键“一”怎么办。这可能吗?我已经更新了问题
  • @Outlooker 我创建的函数将数组作为参数。该数组将包含要从任何级别的嵌套对象中删除的所有键。你想要获取数组中所有键的函数吗?
  • 您提供的功能一流。但我只是想知道如果对象的深度已知,是否可以使用解构来实现这一点
  • @Outlooker 我认为没有办法。因为没有办法解构嵌套对象的所有属性。
  • 感谢@Maheer 的帮助。赞赏。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-12
  • 2021-08-16
  • 2020-06-23
  • 2019-06-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多