简体   繁体   English

JavaScript - 将源 Object 的属性扩展到目标 Object

[英]JavaScript - Extend Properties of Source Object to Destination Object

I've got this problem for precourse for a bootcamp:我在训练营前遇到了这个问题:

// Assigns own enumerable properties of source object(s) to the destination
// object. Subsequent sources overwrite property assignments of previous sources.
// extend({ 'user': 'barney' }, { 'age': 40 }, { 'user': 'fred' });
// should return ->  { 'user': 'fred', 'age': 40 }
// BONUS: solve with reduce

I've seen other questions on here solve this successfully using reduce (which I am still learning).我在这里看到其他问题使用 reduce 成功解决了这个问题(我仍在学习)。 However - I am trying to figure out why exactly the methods I used are being marked as incorrect by the testing site I'm given.但是 - 我试图弄清楚为什么我使用的方法被我给出的测试站点标记为不正确。

Here is a correct answer given on another question on here:这是对此处另一个问题的正确答案:

function extend(...destination) {
  return destination.reduce(function(acc, val){
    var keys = Object.keys(val),
    key = null;
    for(var keyIdx = 0, len = keys.length; keyIdx < len; keyIdx++){
      key = keys[keyIdx];
      acc[key] = val[key];
    }
    return acc;
  });

Here are two of my answers that both got the same output - but were marked wrong.这是我的两个答案,它们都得到了相同的 output - 但被标记为错误。 I assume this is because of object reference, but I am having trouble finding the exact problem.我认为这是因为 object 参考,但我很难找到确切的问题。

function extend(...destination) {
  const newObj = {};
  destination.forEach(x => {
    var keys = Object.keys(x);
    for (let i = 0; i < keys.length; i++){
      const key = keys[i];
      newObj[key] = x[key];
    }
  });

  return newObj;

and

function extend(...destination) {
  const newObj = {};
  destination.forEach(x => {
    Object.assign(newObj, x);
  });
  return newObj;

Thanks in advance.提前致谢。 Sorry if this is a dumb question - my first ask on here.对不起,如果这是一个愚蠢的问题 - 我在这里的第一个问题。

The first argument to the function is the destination object that should be modified in place. function 的第一个参数是应就地修改的目标 object。 You're creating a new object instead of modifying the first object in place.您正在创建一个新的 object,而不是修改第一个 object。

Split the arguments into a single destination and spread sources .将 arguments 拆分为单个destination并传播sources Then your loop can be used to update destination .然后您的循环可用于更新destination

 function extend(destination, ...sources) { sources.forEach(x => { var keys = Object.keys(x); for (let i = 0; i < keys.length; i++) { const key = keys[i]; destination[key] = x[key]; } }); return destination; } const obj = { 'user': 'barney' }; extend(obj, { 'age': 40 }, { 'user': 'fred' }); console.log(obj);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM