遍历递归json树并合并
Traverse recursive json tree and merge
我正试图遍历如下(json2)所示的递归json树,如果标识符匹配如下,则与另一个json(json)合并。请注意,只要对象可用,它就可能有或的对象 注意:标识符值始终是唯一的 我浏览了underscore.js库,但找不到任何符合此要求的函数。在正常的列表情况下,findWhere将足以解决问题,但事实并非如此,因为它具有多级层次结构。 json2: json1: 合并后{
"identifier1": "123456",
"identifier2": "234567"
}
{
subtopic: [
{
"title": "title 1",
"subtitle": "title 2",
"objects": [{
"title": "123"
"label": "456"
"objects": [
{
"identifier": "identifier1",
"object": {
"object-1": "123",
"object-2": "456"
}
},
{
"identifier": "identifier2",
"object": {
"object-1": "123",
"object-2": "456"
}
}
]
}]
},
{
...
...
Similar as above
},
]
}
{
subtopic: [
{
"title": "title 1",
"subtitle": "title 2",
"objects": [{
"title": "123"
"label": "456"
"objects": [
{
"result": "123456",
"identifier": "identifier1",
"object": {
"object-1": "123",
"object-2": "456"
}
},
{
"result": "234567"
"identifier": "identifier2",
"object": {
"object-1": "123",
"object-2": "456"
}
}
]
}]
},
{
...
...
Similar as above
},
]
}
至少您需要一些迭代和递归样式来获得用于设置新属性的正确内部对象。
function merge(array, object) {
Object.keys(object).forEach(function (k) {
function iter(a) {
if (a.identifier === k) {
r = a;
return true;
}
return Array.isArray(a.objects) && a.objects.some(iter);
}
var r;
array.some(iter);
if (r) {
r.result = object[k];
}
});
}
var object2 = { "identifier1": "123456", "identifier2": "234567" },
object1 = { subtopic: [{ "title": "title 1", "subtitle": "title 2", "objects": [{ "title": "123", "label": "456", "objects": [{ "identifier": "identifier1", "object": { "object-1": "123", "object-2": "456" } }, { "identifier": "identifier2", "object": { "object-1": "123", "object-2": "456" } }] }] }] };
merge(object1.subtopic, object2);
document.write('<pre>' + JSON.stringify(object1, 0, 4) + '</pre>');
- JSON重构(合并内容)与javascript
- 将两个Json提要合并为一个,并按时间排序
- 如何使用jQuery合并两个json对象
- 遍历递归json树并合并
- 如何将多个 Blender JSON 模型合并到一个 Three.js Object3D 对象中
- 合并两个嵌套的JSON数组
- 是否有任何功能可以合并两个JSON数据集并替换旧信息?(节点.JS)
- 如果对象使用 reduce、forEach 或筛选器共享属性值,则合并 JSON 数组中的对象
- 合并 json 对象并保留重复的键
- 流类型和合并 json 对象
- 合并JSON并覆盖值
- 删除重复项并合并JSON对象
- D3:合并JSON对象条目
- 合并JSON数组
- 以更简单的方式合并JSON
- 按键合并JSON数据
- 如何在javascript中合并json数组与相同的值
- 合并JSON对象数组并使用Javascript进行排序
- 无法在JS中合并JSON
- 使用相同的“键”合并JSON对象,并使用JavaScript添加它们的“值”