2016-04-08 81 views
-1

我有2个json格式,即jsonA和jsonB,我想将其合并到jsonC中,如下所示。 欣赏是否有人能告诉我如何去做。将集合合并到json数组

jsonA

{ 
    "text1": "Hello", 
    "text2": "Hi", 
    "text3": "There" 
} 

jsonB

[ 
    { 
     "id": "text1", 
     "category": "Big" 
    }, 
    { 
     "id": "text2", 
     "category": "Medium" 
    }, 
    { 
     "id": "text3", 
     "category": "Small" 
    }, 
] 

最终

[ 
    { 
     "id": "text1", 
     "category": "Big", 
     "message": "Hello" 
    }, 
    { 
     "id": "text2", 
     "category": "Medium", 
     "message": "Hi" 
    }, 
    { 
     "id": "text3", 
     "category": "Small", 
     "message": "There" 
    } 
] 
+1

JSON是*文本符号*进行数据交换。如果你正在处理JavaScript源代码,而不是处理*字符串*,那么你并没有处理JSON。你在那里有一个对象和一个数组。 –

+1

刺探它,如果遇到麻烦,请提出有关您遇到的问题的具体问题。 –

+1

是''id“:”text1“'总是一样吗? –

回答

1

新阵列的解决方案。

基本上它迭代数组并为每个找到的对象构建一个新的对象。它增加了一个新的属性message与想要的内容形式objectA

var objectA = { "text1": "Hello", "text2": "Hi", "text3": "There" }, 
 
    objectB = [{ "id": "text1", "category": "Big" }, { "id": "text2", "category": "Medium" }, { "id": "text3", "category": "Small" }], 
 
    objectC = objectB.map(function (a) { 
 
     return { 
 
      id: a.id, 
 
      category: a.category, 
 
      message: objectA[a.id] 
 
     }; 
 
    }); 
 

 
document.write('<pre>' + JSON.stringify(objectC, 0, 4) + '</pre>');

Soulution用于突变的阵列。

该解决方案获取数组并在循环中添加一个新属性,其值为objectA

var objectA = { "text1": "Hello", "text2": "Hi", "text3": "There" }, 
 
    objectB = [{ "id": "text1", "category": "Big" }, { "id": "text2", "category": "Medium" }, { "id": "text3", "category": "Small" }]; 
 

 
objectB.forEach(function (a) { 
 
    a.message = objectA[a.id]; 
 
}); 
 

 
document.write('<pre>' + JSON.stringify(objectB, 0, 4) + '</pre>');

-1

首先,你需要遍历第二JSON数组。比遍历第一个json并比较索引。如果索引匹配,则将新属性添加到第2个json。

下面是完整的例子:

VAR jsonA = '{ “text1” 中的: “你好”, “text2” 中的: “你好”, “text3” 中: “有”}'; var jsonB ='[{“id”:“text1”,“category”:“Big”},{“id”:“text1”,“category”:“Medium”},{“id” “text1”,“category”:“Small”}]';

jsonA = JSON.parse(jsonA); 
jsonB = JSON.parse(jsonB); 

for(var i=0;i<jsonB.length;i++){ 
    for(var j in jsonA){    
     if(j == ("text"+(i+1))){ 
      jsonB[i].message = jsonA[j];     
     }    
    } 
} 

console.log(JSON.stringify(jsonB)); 

输出:[{ “ID”: “文本1”, “类别”: “大”, “消息”: “你好”},{ “ID”: “文本1”, “类别”:”中等“,”消息“:”Hi“},{”id“:”text1“,”类别“:”小“,”消息“:”There“}]