这很难说清楚,但希望我有道理。假设您有一个像这样的数组:
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: [],
}]
我将如何实现?
答案 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;