如何用另一个数组的值更新一个数组,而不覆盖任何键?

时间:2019-04-06 22:26:50

标签: javascript arrays object

这很难说清楚,但希望我有道理。假设您有一个像这样的数组:

  firstArray: [
    {
      firstName: '',
      age: null,
      gender: null,
      preferences: []
    }
  ],

您想使用另一个内容(不覆盖任何键)来更新此数组,例如:

const arrayToPushToFirstArray = [{
     age: 1,
     firstName: "Billy"
     gender: "girl"
    },
    {
     age: 2
     firstName: "Daniel"
     gender: "boy"
    }]

firstArray如下:

const firstArray = [{
     age: 1
     firstName: "Billy"
     gender: "girl"
     preferences: []
    },
    {
     age: 2
     firstName: "Daniel"
     gender: "boy"
     preferences: [],
    }]

我将如何实现?

1 个答案:

答案 0 :(得分:1)

您需要像JavaScript equivalent of jQuery's extend method

中那样扩展数组

您的示例将像这样https://jsfiddle.net/06mwgqsf/

var firstArray = [{
  firstName: '',
  age: null,
  gender: null,
  preferences: []
}];

var arrayToPushToFirstArray = [{
    age: 1,
    firstName: "Billy",
    gender: "girl"
  },
  {
    age: 2,
    firstName: "Daniel",
    gender: "boy"
  }
];

function extend() {
  for (var i = 1; i < arguments.length; i++)
    for (var key in arguments[i])
      if (arguments[i].hasOwnProperty(key))
        arguments[0][key] = arguments[i][key];
  return arguments[0];
}

var mask = firstArray[0];
var tmpArray = [];

for (var x = 0; x < arrayToPushToFirstArray.length; x++) {
  var tmpObj = extend({}, mask, arrayToPushToFirstArray[x]);
  tmpArray.push(tmpObj);
}

firstArray = tmpArray;