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

4

假设我有一个对象:

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

我看过解构对象的例子,但我想知道是否可以对嵌套对象进行操作。使用解构来完成这样的操作是否可行,如果不行,那么最有效的方法是什么呢?

1
你需要这个来处理任何深度的结构,还是只针对某些特定已知的结构,比如你所描述的那个? - Shidersz
目前为止,已知的结构应该是没问题的。我稍微更新了一下我的问题。 :) - Outlooker
以什么方式高效? - Joel Cornett
3个回答

5

使用类似解构的语法来实现这一点的一种方式是:

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)


谢谢您的回复。如果我只需要嵌套对象中的键“one”,这是否可行? - Outlooker
我已经更新了问题。你能否请看一下那里 :) - Outlooker
1
@Outlooker 或许你可以在这种情况下用 ...({one} = myObj.others, {one}) 替换 ...myObj.others - Shidersz
@Outlooker 抱歉回复晚了 - 我刚刚更新了你的问题的答案,这有帮助吗? - Dacre Denny
@DacreDenny 当然,感谢你的所有帮助 :) - Outlooker

4

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


谢谢您的回复。如果我只需要嵌套对象中的键“one”,这是否可行?我已更新问题。 - Outlooker
你可以使用Object.assign({}, {name, age}, {one: others.one})作为函数体。但是,听起来你正在寻找一个通用函数,它将接受诸如要保留的键的数组,并将递归地复制所有内容(可能会进行扁平化)?你能进一步说明你的要求吗?否则,这就像打“Whack-a-mole”游戏一样。 - ggorlen

2
对于深度未知的对象,您可以尝试使用递归。
- 创建一个函数,该函数将一个对象和要删除的键数组作为参数。 - 在主函数内创建一个带有1个对象参数的helper函数,并创建空对象。 - 使用for..in循环遍历obj的属性。 - 检查key是否不存在于要删除的键数组中,然后
- 如果值是对象,则调用函数进行递归 - 如果不是对象,则将其添加到结果对象中。
- 最后返回结果对象。
代码将把深度未知的对象转换为普通对象,您还可以从嵌套对象中删除键。"Original Answer"翻译成"最初的回答"。

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)


谢谢您的回复。如果我只需要已知深度嵌套对象中的键“one”,这是否可行?我已更新问题。 - Outlooker
@Outlooker 我创建的函数以数组作为参数。该数组将包含要从任何级别的嵌套对象中删除的所有键。您需要获取所有键的函数吗? - Maheer Ali
你提供的函数非常好。但我只是想知道如果对象的深度已知,是否可以使用解构来实现。 - Outlooker
@Outlooker 我认为没有办法。因为无法解构嵌套对象的所有属性。 - Maheer Ali
感谢@Maheer的帮助,非常感激。 :) - Outlooker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接