【发布时间】:2016-03-02 17:53:45
【问题描述】:
下面的函数看起来是正确的,但它工作不正确
$.when(
$.getJSON('compare/As_edit.json'), $.getJSON('compare/As_old.json'))
.then(function (a,b) {
//return $.extend(a, b);
console.log($.extend(a, b));
})
在控制台日志中我看到:
Object {text: "As", icon: "icons/tree.png", children: Array[1]}
虽然它应该是“children: Array2”
我的文件看起来像:
文件1
{
"text": "As",
"icon": "icons/tree.png",
"children": [
{
"text": "Class1",
"children": [
{
"text": "Intern1",
"-ORDER": "2",
"children": [
{
"name": "--TRT",
"text": "Name of Intern"
}
]
},
{
"text": "Intern2",
"-ORDER": "2",
"children": [
{
"name": "--TRT",
"text": "Name of Intern"
}
]
}
]
}
]
}
文件2
{
"text": "As",
"icon": "icons/tree.png",
"children": [
{
"text": "Class2",
"children": [
{
"text": "Intern3",
"-ORDER": "2",
"children": [
{
"name": "--TRT",
"text": "Name of Intern"
}
]
},
{
"text": "Intern4",
"-ORDER": "2",
"children": [
{
"name": "--TRT",
"text": "Name of Intern"
}
]
}
]
}
]
}
我想在输出中看到
{
"text": "As",
"icon": "icons/tree.png",
"children": [
{
"text": "Class1",
"children": [
{
"text": "Intern1",
"-ORDER": "2",
"children": [
{
"name": "--TRT",
"text": "Name of Intern"
}
]
},
{
"text": "Intern2",
"-ORDER": "2",
"children": [
{
"name": "--TRT",
"text": "Name of Intern"
}
]
}
]
},
{
"text": "Class2",
"children": [
{
"text": "Intern3",
"-ORDER": "2",
"children": [
{
"name": "--TRT",
"text": "Name of Intern"
}
]
},
{
"text": "Intern4",
"-ORDER": "2",
"children": [
{
"name": "--TRT",
"text": "Name of Intern"
}
]
}
]
}
]
}
但我只从 file2 中的对象获取输出 怎么了?
这是一个fiddle 示例
在Merge 2 arrays of objects 上检查参考后,我使用了下一个代码
$.when(
$.getJSON('compare/Astella_edit.json'), $.getJSON('compare/Astella_old.json'))
.then(function (a,b) {
var arr3 = [];
for (var i in a) {
var shared = false;
for (var j in b)
if (b[j].children == a[i].children) {
console.log('['+ (b[j].children == a[i].children) +']');
shared = true;
break;
}
if (!shared) arr3.push(a[i])
}
arr3 = arr3.concat(b);
console.log(arr3);
//return arr3;
})
它几乎正确地合并到我身上
[Object, Object, "success", Object]
所以第一个对象是file1,第二个是file2
生成的 JSON 中的“成功”是什么意思,第三个对象来自哪里?
【问题讨论】:
-
尝试 console.log()-ing a 和 b 分别查看回调函数返回的内容
-
你需要做深度扩展...阅读文档...试试
$.extend(true,a, b) -
@glcheetham,控制台显示 a - [Object, "success", Object]" 和 file1 内,对于 b - "[Object, "success", Object]" 在 file2 内
-
@charlietfl,深度扩展也一样
-
使用示例数据创建演示
标签: javascript jquery arrays json