gpt4 book ai didi

Javascript 遍历对象并在子对象中插入丢失的键

转载 作者:行者123 更新时间:2023-11-30 07:37:55 28 4
gpt4 key购买 nike

我需要同步两个 javascript 对象,我想用 object1 中缺少的键填充 object2,而不替换现有的,即使是嵌套的:

var object1 = {
firstName: "Marco",
lastName: "Rossi",
favoriteFood: {firstCourse: "pasta", secondCourse: "salsiccia"},
favoriteDrink: "Vino",
favoriteSong: "O sole mio"
}

var object2 = {
firstName: "Marco",
lastName: "Rossi",
favoriteFood: {firstCourse: "pasta"},
favoriteSong: "Viaggiare"
}

我真的不知道如何进入嵌套键。特别是要继续检查内部嵌套,如果你有 5 个嵌套或类似的东西怎么办我知道如何处理第一层但不能再往下。

objec2 的期望结果是

var object2 = {
firstName: "Marco",
lastName: "Rossi",
favoriteFood: {firstCourse: "pasta", secondCourse: "salsiccia"},
favoriteDrink: "Vino",
favoriteSong: "Viaggiare"
}

预先感谢您的帮助。

最佳答案

您需要编写递归函数来处理嵌套对象。也许是这样的:

var object1 = {
firstName: "Marco",
lastName: "Rossi",
favoriteFood: {firstCourse: "pasta", secondCourse: "salsiccia"},
favoriteMovie: {rating: 7, title: "Monday"},
favoriteDrink: "Vino",
favoriteSong: "O sole mio"
}

var object2 = {
firstName: "Marco",
lastName: "Rossi",
favoriteFood: {firstCourse: "pasta"},
favoriteSong: "Viaggiare"
}

function fillObject(from, to) {
for (var key in from) {
if (from.hasOwnProperty(key)) {
if (Object.prototype.toString.call(from[key]) === '[object Object]') {
if (!to.hasOwnProperty(key)) {
to[key] = {};
}
fillObject(from[key], to[key]);
}
else if (!to.hasOwnProperty(key)) {
to[key] = from[key];
}
}
}
}

fillObject(object1, object2);

alert( JSON.stringify(object2, null, ' ') );

注意:如果您想知道这一行 Object.prototype.toString.call(from[key]) - 这是为了可靠地检查该值是一个对象,因为 typeof null 还报告 object

关于Javascript 遍历对象并在子对象中插入丢失的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26546090/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com