Не получается глубокая копия JS
const incoming0bj = {
formatted_address : "Washington Square, New York, NY 10012, Сполучені Штати Америки",
geometry: {
location: {
lat: 40.7308838,
lng: -73.997332
},
viewport: {
northeast: {
lat: 40.7333674,
lng: -73.99379435000002
},
southwest: {
lat: 40.72847220000001,
lng: -74.00132615
}
}
},
name: "Washington Square Park"
};
let outgoing0bj = {};
for (let key in incoming0bj) {
outgoing0bj[key] = incoming0bj[key]
if (typeof incoming0bj[key] === 'object') {
for (keys in incoming0bj[key]) {
outgoing0bj[key][keys] = incoming0bj[key][keys]
}
}
}
console.log(outgoing0bj)
Ответы (3 шт):
Автор решения: entithat
→ Ссылка
const incoming0bj = {
formatted_address: "Washington Square, New York, NY 10012, Сполучені Штати Америки",
geometry: {
location: {
lat: 40.7308838,
lng: -73.997332
},
viewport: {
northeast: {
lat: 40.7333674,
lng: -73.99379435000002
},
southwest: {
lat: 40.72847220000001,
lng: -74.00132615
}
}
},
name: "Washington Square Park"
};
const newObj = {...incoming0bj};
incoming0bj.name = '';
console.log(incoming0bj);
console.log(newObj);
Автор решения: Alexander Lonberg
→ Ссылка
Глубокую копию делают через рекурсию
const incoming0bj = {
formatted_address: "Washington Square, New York, NY 10012, Сполучені Штати Америки",
geometry: {
location: { lat: 40.7308838, lng: -73.997332 },
viewport: {
northeast: { lat: 40.7333674, lng: -73.99379435000002 },
southwest: [1, 2, 3, { a: 456 }]
}
},
name: "Washington Square Park"
}
// Для примера делаем ссылку на самого себя
incoming0bj.foo = incoming0bj
const isObject = (v) => typeof v === 'object' && v !== null
const isArray = Array.isArray
function copy(o, parent = [/* избегаем бесконечного копирования */]) {
if (parent.includes(o)) {
return null // !!! любое значение
}
if (isArray(o)) {
parent.push(o)
let a = []
for (let i of o) {
a.push(copy(i, parent))
}
parent.pop()
return a
}
if (isObject(o)) {
parent.push(o)
let a = {}
for (let [p, v] of Object.entries(o)) {
a[p] = copy(v, parent)
}
parent.pop()
return a
}
return o
}
console.log(
JSON.stringify(copy(incoming0bj), null, 2)
)
UPD: Изменил что'б небыло бесконечного копирования
Автор решения: Vladyslav Herasymenko
→ Ссылка
const incomingObj = {
formatted_address : "Washington Square, New York, NY 10012, Сполучені Штати Америки",
geometry: {
location: {
lat: 40.7308838,
lng: -73.997332
},
viewport: {
northeast: {
lat: 40.7333674,
lng: -73.99379435000002
},
southwest: {
lat: 40.72847220000001,
lng: -74.00132615
}
}
},
name: "Washington Square Park"
};
function getCopyObj(source) {
let result = {};
for (let key in source) {
result[key] = {};
if (typeof source[key] !== 'object') {
result[key] = source[key]
continue;
}
result[key] = getCopyObj(source[key]);
}
return result;
}
console.log(getCopyObj(incomingObj));
У меня более компактно получилось.