我们必须编写一个JavaScript函数,比如说extract()
将一个对象的属性提取到另一个对象,然后从原始对象中删除它们。
例如-
如果obj1和obj2是两个对象,则
obj1 = {color:"red", age:"23", name:"cindy"} obj2 = extract(obj1, ["color","name"])
通过提取函数后,它们应该变成-
obj1 = { age:23 } obj2 = {color:"red", name:"cindy"}
因此,让我们为该函数编写代码-
const obj = { name: "Rahul", job: "Software Engineer", age: 23, city: "Mumbai", hobby: "Reading books" }; const extract = (obj, ...keys) => { const newObject = Object.assign({}); Object.keys(obj).forEach((key) => { if(keys.includes(key)){ newObject[key] = obj[key]; delete obj[key]; }; }); return newObject; }; console.log(extract(obj, 'name', 'job', 'hobby')); console.log(obj);
输出结果
控制台中的输出将为-
{ name: 'Rahul', job: 'Software Engineer', hobby: 'Reading books' } { age: 23, city: 'Mumbai' }