对象:1
{
"sourcePath": "vv",
"targetPath": "bb"
}
我获得了像对象1这样的键值对,并且我已经拥有了像Object 2这样的嵌套对象
对象:2
{
"user": "hdpsrvc",
"update": "13/06/2016 17:43:22",
"template": "template_1",
"formBody": [
{
"tabIndex": 0,
"type": "text",
"name": "sourcePath",
"label": "Source path"
},
{
"tabIndex": 1,
"type": "text",
"name": "targetPath",
"label": "Target path"
}
],
}
我希望将对象1的键值对推送到如下所示的嵌套对象(请参阅formBody
下的红色标记粗体键值对)
{
"user": "hdpsrvc",
"update": "13/06/2016 17:43:22",
"template": "template_1",
"formBody": [
{
"tabIndex": 0,
"type": "text",
"name": "sourcePath",
"label": "Source path",
"sourcePath": "vv"
},
{
"tabIndex": 1,
"type": "text",
"name": "targetPath",
"label": "Target path",
"targetPath": "bb"
}
],
}
答案 0 :(得分:0)
如果您只有这两个值推,那么只需按照以下方式分配即可轻松完成。
假设JSON 1存储在变量var jsonOne
中,而JSON 2存储在变量var jsonTwo
中。然后
jsonTwo.formBody[0].sourcePath = jsonOne.sourcePath;
jsonTwo.formBody[1].targetPath = jsonOne.targetPath;
或者,如果您有更多的值要推送,那么您可以编写for循环并形成匹配的算法。在下面的代码中我与标签匹配;
for (i = 0; i < jsonTwo.formBody.length; i++) {
var temp = jsonTwo.formBody[i].label;
if (temp === 'Source path') {
jsonTwo.formBody[i].sourcePath = jsonOne.sourcePath;
} else {
jsonTwo.formBody[i].targetPath = jsonOne.targetPath;
}
}
答案 1 :(得分:0)
你可以试试这个:
var obj1 = {
"sourcePath": "vv",
"targetPath": "bb"
};
var obj2 = {
"user": "hdpsrvc",
"update": "13/06/2016 17:43:22",
"template": "template_1",
"formBody": [
{
"tabIndex": 0,
"type": "text",
"name": "sourcePath",
"label": "Source path"
},
{
"tabIndex": 1,
"type": "text",
"name": "targetPath",
"label": "Target path"
}
]};
obj2.formBody = obj2.formBody.map((item , ind) => Object.assign(
item,
{[Object.keys(obj1)[ind]]: obj1[Object.keys(obj1)[ind]]}
));
console.log(obj2);
甚至:
var obj1 = {
"sourcePath": "vv",
"targetPath": "bb"
};
var obj2 = {
"user": "hdpsrvc",
"update": "13/06/2016 17:43:22",
"template": "template_1",
"formBody": [
{
"tabIndex": 0,
"type": "text",
"name": "sourcePath",
"label": "Source path"
},
{
"tabIndex": 1,
"type": "text",
"name": "targetPath",
"label": "Target path"
}
]};
obj2.formBody = obj2.formBody.map(item => Object.assign(
item,
{[item.name]: obj1[item.name]}
));
console.log(obj2);