如何在不更改其他属性的情况下替换对象属性,如果分配的对象数量不均衡,则复制其他属性?
我想这个问题可能没有任何意义。这个例子可以解释一切。让我说:
var oldData = {
fruits: fruits,
veggies: [{
sweet: false,
colour: red,
data: [1, 2, 3]
}]
};
var newData = {
veggies: [{
sweet: true,
data: [99, 100, 101]
},
{
sweet: false,
data: [888, 777, 665],
}]
};
var standardColor = "blue";目标是:
问题:
我的拙劣尝试:
function replaceVeggies (newData) {
oldData.veggies = newData.veggies
};发布于 2018-03-20 12:41:01
这应该对你有用。
我添加了一些额外的数据来测试一些需求。
var oldData = {
fruits: "fruits",
veggies: [{
sweet: false,
colour: "red",
data: [1, 2, 3]
},
{
sweet: true,
// colour: "red",
data: [1, 2, 3]
}
]
};
var newData = {
veggies: [{
sweet: true,
data: [99, 100, 101]
},
{
sweet: false,
data: [888, 777, 665]
},
{
sweet: false,
data: [444, 558, 333]
}
]
};
var standardColor = "blue";
// Iterate through the newData object
for (var i = 0; i < newData.veggies.length; i++) {
var newVeggie = newData.veggies[i];
// Check if the index value exists on the old array
if (oldData.veggies[i] !== null && (typeof oldData.veggies[i] !== "undefined")) {
// Always replace data
oldData.veggies[i].data = newVeggie.data;
// Always replace sweet value
oldData.veggies[i].sweet = newVeggie.sweet;
// Replace colour if exists in new data
if (newVeggie.colour !== undefined) {
oldData.veggies[i].colour = newVeggie.colour;
} else {
// If old data didn't have colour value set default
if (oldData.veggies[i].colour == undefined) {
oldData.veggies[i].colour = standardColor;
}
}
} else {
// Check if the colour is null
if (newData.veggies[i].colour == undefined) {
newData.veggies[i].colour = standardColor;
}
// Assign the new veggie directly
oldData.veggies[i] = newVeggie;
}
console.log("Veggie " + i);
// Iterate over the properties
Object.keys(oldData.veggies[i]).forEach(function(key) {
console.log(" " + key + ": " + oldData.veggies[i][key]);
});
}
发布于 2018-03-20 10:24:51
JS内置的Object.assign为您处理这个问题:
const x = {
y: 10,
z: 20
}
console.log(JSON.stringify(x))
console.log(JSON.stringify(Object.assign(x, { y : 30, a: 45 })))
https://stackoverflow.com/questions/49381415
复制相似问题