让obj1 =obj1.json**
{
"stores": {
"city1": [
{
"address": null,
"firstName": null,
"lastName": null
}
]
}
}让obj2 = obj2.json**
{
"stores": {
"city1": [
{
"address": 13, Landiling,
"firstName": Robot,
"lastName": Tom,
"phone": 12345678,
"email": test@,
"manager": tim
}
]
}
}下面是我使用obj2更新obj1值的代码。
result = Object.keys(obj1.stores.city1[0]);
for (var i = 0; i< result.length; i++ ) {
console.log(result[i]);
console.log(JSON.stringify(obj1.stores.city1[0].result[i]));
obj1.stores.city1[0].result[i]=obj2.stores.city1[0].result[i];
}我可以使用上面的代码从obj1获得子键,但不能将值更新回obj1。因为它显示为'i‘没有定义或接收到未定义的结果。
发布于 2020-08-01 00:00:59
您需要知道当前的城市关键字,才能在更新对象中查找城市。
中的相应索引处分配更新对象
不确定是否要复制所有属性,但没有示例输出。
const toBeUpdated = {
"stores": {
"city1": [{
"address": null,
"firstName": null,
"lastName": null
}]
}
}
const updateInfo = {
"stores": {
"city1": [{
"address": "13, Landiling",
"firstName": "Robot",
"lastName": "Tom",
"phone": "12345678",
"email": "test@",
"manager": "tim"
}]
}
}
Object.keys(toBeUpdated.stores).forEach(cityKey => {
toBeUpdated.stores[cityKey].forEach((city, index) => {
Object.assign(city, { ...updateInfo.stores[cityKey][index] });
});
});
console.log(toBeUpdated);.as-console-wrapper {
top: 0;
max-height: 100% !important;
}
发布于 2020-08-01 00:08:13
我稍微修改了你的代码,让它在我的本地机器上运行。以下是正在实现您想要实现的目标的工作代码。
const obj1 = {
stores: {
city1: [
{
address: null,
firstName: null,
lastName: null
}
]
}
}
const obj2 = {
stores: {
city1: [
{
address: '13, Landiling',
firstName: 'Robot',
lastName: 'Tom',
phone: 12345678,
email: 'test@',
manager: 'tim'
}
]
}
}
const result = Object.keys(obj1.stores.city1[0])
console.log('Keys: ', result)
for (var i = 0; i < result.length; i++) {
console.log('Key: ', result[i])
console.log('Value:', JSON.stringify(obj1.stores.city1[0][i]))
obj1.stores.city1[0][result[i]] = obj2.stores.city1[0][result[i]]
}
console.log('object 1: ', JSON.stringify(obj1))
console.log('object 2: ', JSON.stringify(obj2))下面是您的代码行:
obj1.stores.city1[0].result[i]=obj2.stores.city1[0].result[i];正被翻译为
obj1.stores.city1[0].result.<value of i> = obj2.stores.city1[0].result.<value of i>;您正在city1对象上查找不存在的result属性,然后您正在尝试访问result对象上的number属性(其本身是未定义的)。因此,您正在尝试访问未定义对象的未定义属性。这就是您无法更改obj1的原因。我希望我的回答能澄清。
https://stackoverflow.com/questions/63194992
复制相似问题